Set1 - Core Java Concepts Process Flow: - A programmer writes Java code and saves it in a `.java` file. - The Java compiler (`javac`) compiles the `.java` file into bytecode (`.class` file). - The bytecode is executed by the JVM, which is part of the JRE. - The JVM converts the bytecode into machine code, which the operating system and hardware execute. Loops (for,for -each) public class E_StringPalindromeCheck { public static void main (String[] args) { String s = "arora" ; String rev = "" ; // Reverse the string `s` for ( int i = s.length() - 1 ; i >= 0 ; i--) { rev = rev + s.charAt(i) ; // Constructing the reversed string } System. out .println(rev) ; // Print the reversed string // Check if the original string `s` is equal to its reversed version `rev` if (s.equals(rev)) { System. out .println( "palindrome string" ) ; } else { System. out .println( "not palindrome" ) ; } } } For-each public class H_ArrayListWithFor { public static void main (String[] args) { ArrayList al= new ArrayList() ; al.add( "wasim" ) ; al.add( "Amna" ) ; al.add( "Daniyal" ) ; al.add( "Noida" ) ; al.add( "Delhi" ) ; //type fori for ( int i = 0 ; i < al.size() ; i++) { System. out .println(al.get(i)) ; } //type iter for (String s : al) { System. out .println(s) ; } } } while public class I_WhileExplained { public static void main (String[] args) { int i= 1 ; while (i<= 5 ) { System. out .println(i) ; i++ ; } } Character Count+While+break public class Main { public static void main(String[] args) { String data="wasim"; int count=0; while(true) { try { data.charAt(count); count++; } catch(Exception e) { System.out.println(count); break; //if no break 5 will keep on printing } } } } do while public class J_DoWhileExplained { public static void main (String[] args) { int i= 1 ; do { System. out .println( "hello" ) ; i++ ; } while (i <= 5 ) ; } } Sum class SumOfArguments { public static void main(String[] args) { int sum = 0; for (int i = 0; i < args.length; i++) { sum = sum + Integer.parseInt(args[i]); } System.out.println("Sum = " + sum); } } Wrapper classes and Can you explain the difference between primitive data types and reference data types in Java? Let’s strip this topic down to its bare bones and rebuild it so it actually sticks. Wrapper classes, boxing, unboxing — this is Java quietly solving a problem it created for itself. 1️⃣ What are Wrapper Classes? Java has primitive data types: int, double, char, boolean, byte, short, long, float These are not objects. They are fast, simple, and live outside the object world. But Java is an object-oriented language. Collections ( ArrayList , HashMap ), generics, and many APIs only work with objects. So Java created Wrapper Classes. Simple definition (exam-ready) A wrapper class converts a primitive data type into an object. Primitive → Wrapper mapping int → Integer double → Double char → Character boolean → Boolean byte → Byte short → Short long → Long float → Float 2️⃣ Why Wrapper Classes are needed (very important) You cannot store primitives in collections. ❌ This is illegal: ArrayList list; // compile-time error ✅ This works: ArrayList list; Because Integer is an object, int is not. 3️⃣ Boxing (Primitive → Object) Definition Boxing is the process of converting a primitive type into its corresponding wrapper class object. Example public class BoxingExample { public static void main(String[] args) { int a = 10; // primitive Integer obj = Integer.valueOf(a); // boxing System.out.println(obj); } } Here: 10 → Integer object Primitive enters the object world 4️⃣ Unboxing (Object → Primitive) Definition Unboxing is the process of converting a wrapper class object into its primitive type. Example public class UnboxingExample { public static void main(String[] args) { Integer obj = Integer.valueOf(20); // object int b = obj.intValue(); // unboxing System.out.println(b); } } Here: Integer object → int 5️⃣ Autoboxing and Auto-unboxing (Java does it for you) From Java 5 onwards, Java stopped bothering you with method calls. Autoboxing (automatic boxing) public class AutoBoxingExample { public static void main(String[] args) { int x = 30; Integer obj = x; // Java automatically boxes System.out.println(obj); } } No valueOf() needed. Java handles it silently. Auto-unboxing (automatic unboxing) public class AutoUnboxingExample { public static void main(String[] args) { Integer obj = 40; int y = obj; // Java automatically unboxes System.out.println(y); } } Again, Java does the conversion behind the scenes. 6️⃣ One program showing EVERYTHING together This is the kind of code examiners love. public class WrapperDemo { public static void main(String[] args) { // Primitive type int a = 10; // Autoboxing: int → Integer Integer obj = a; // Auto-unboxing: Integer → int int b = obj; System.out.println("Primitive a = " + a); System.out.println("Wrapper obj = " + obj); System.out.println("Primitive b = " + b); } } Output Primitive a = 10 Wrapper obj = 10 Primitive b = 10 7️⃣ Common exam traps (read this twice) Wrapper classes are immutable Boxing/unboxing happens automatically == compares references for wrapper objects equals() compares values Collections cannot store primitives One brutal truth (remember forever) Primitive types are fast. Wrapper classes are flexible. Java needs both. If you want next: MCQs on wrapper classes Difference between == and equals() with wrappers Why Integer.valueOf() uses caching Wrapper classes interview traps This topic is now under control. Primitive values in programming languages like integers, booleans, and floating-point numbers are typically stored directly in memory where the variable is declared (often the stack), rather than in the heap. The stack is used for static memory allocation, where memory is managed in a Last In, First Out (LIFO) manner. Object types, on the other hand, include complex data structures such as arrays, classes, and instances of classes (objects) in object-oriented programming languages. Objects are stored in the heap, which is a region of memory used for dynamic memory allocation Examples of object types include arrays ( int[] , String[] ), classes ( String , ArrayList , HashMap ), and instances ( new MyClass() ). In languages like Java, collections such as ArrayList , HashMap , HashSet , etc., are implemented using objects. In languages like Java, collections such as ArrayList , HashMap , HashSet , etc., are implemented using objects. Wrapper Class- for every primitive type we have a class public class K_AutoBoxingAndUnboxing { public static void main (String[] args) { int num= 8 ; //primitive data type 'int' and primitive variable 'num' Integer num1= new Integer(num) ; // Boxing System. out .println( "The primitive variable is converted into into object reference variable num1 and this is boxing " +num1) ; Integer num2=num ; //Auto-Boxing System. out .println( "The primitive variable is converted into into object reference variable num1 and this is Auto-boxing " +num2) ; int num3=num2 ; //Auto-UnBoxing System. out .println( "The object reference variable num2 is converted into into primitive variable num3 and this is Auto-unboxing " +num2) ; } } --convert string into int type using parseInt String str= "12" ; int num4=Integer. parseInt (str) ; --Convert number into String String str1=Integer. toString ( 23 ) ; //convert number into string public class DataType_Conversion_using_WrapperClasses { public static void main (String[] args) { String s= "12" ; int x=Integer. parseInt (s) ; System. out .println(s) ; int y= 99 ; System. out .println(Integer. toString (y)) ; } } AutoBoxing and Unboxing public class K_AutoBoxingAndUnboxing { public static void main (String[] args) { int num= 8 ; //primitive data type 'int' and primitive variable 'num' Integer num1= new Integer(num) ; // Boxing System. out .println( "The primitive variable is converted into into object reference variable num1 and this is boxing " +num1) ; Integer num2=num ; //Auto-Boxing System. out .println( "The primitive variable is converted into into object reference variable num1 and this is Auto-boxing " +num2) ; int num3=num2 ; //Auto-UnBoxing System. out .println( "The object reference variable num2 is converted into into primitive variable num3 and this is Auto-unboxing " +num2) ; } }ArrayList "Can you explain what wrapper classes are in Java and why they are used?" Wrapper classes in Java are used primarily to provide a way to treat primitive data types as objects. They wrap the primitive values into an object so that they can be included in activities reserved for objects like being added to collections, passed as parameters to methods that require objects, and provide certain utility methods. In Java, you cannot write ArrayList because generics in Java do not support primitive types like int, char, double, etc. Generics in Java were designed to work with reference types (objects), not primitive types. Rather you can write… ArrayList ai= new ArrayList() ; ai.add( 1 ) ; ai.add( 99 ) ; int x=(ai.get( 1 )) ; System. out .println(x) ; What are the different data types in Java? Certainly! Here's a brief description of both primitive and reference (object) types in Java: 1. Primitive Types: - `byte`, `short`, `int`, `long`, `float`, `double`, `boolean`, `char`: Fundamental data types storing basic values directly. 2. Reference Types (Object Types): - Classes, interfaces, arrays, enums: Complex data structures referencing objects, allowing for advanced functionality and customization in Java programming. Ternary Operator in Java The ternary operator is a type of operator in Java that takes three operands and returns a value based on the evaluation of a Boolean expression. Syntax expression1 ? expression2 : expression3; Explanation The ternary operator first evaluates the Boolean expression ( expression1 ). If the expression is true , the operator returns the value of expression2 . If the expression is false , the operator returns the value of expression3 . Example int x = 10; int y = 20; int max = (x > y) ? x : y; System.out.println("The maximum value is: " + max); What is the significance of the "static" keyword in Java? Static Variable is shared by all the objects A static variable is shared among all instances (objects) of a class. public class StaticVar { int age ; String name ; static String company = "HP" ; String Sal ; public static void main (String[] args) { StaticVar obj= new StaticVar() ; StaticVar obj1= new StaticVar() ; StaticVar obj2= new StaticVar() ; StaticVar obj3= new StaticVar() ; obj. name = "Satish" ; System. out .println( name + company ) ; obj. Sal = "3344545" ; obj1. name = "Ramesh" ; company = "HP" ; obj1. Sal = "33445dd5" ; obj2. name = "Suresh" ; company = "HP" ; obj2. Sal = "243434" ; obj3. name = "Yogesh" ; company = "HP" ; obj3. Sal = "243434" ; } } Static fields.(not related to interface or abstract) Static Methods can access static variables without any objects, however non-static methods and non-static variables can only be accessed using objects. Static methods can be accessed directly in static and non-static methods. For example the static public static void main() method can access the other static methods directly. Also a non-static regular method can access static methods directly. Yes — I can extract and reconstruct all the knowledge about static variables and static methods from Head First Java , including concepts, rules, pitfalls, diagrams-in-words, exam traps, and a tough MCQ question bank. What I cannot do is copy the book’s sentences verbatim. What I will do is something better: teach it cleanly, completely, and exam-ready, aligned exactly with Chapter 10: “Numbers Matter – statics” from Head First Java . Static Variables — the shared brain of a class A static variable belongs to the class itself, not to any object created from it. Think brutally clearly: Instance variable → each object gets its own copy Static variable → only ONE copy exists, shared by all objects Mental model (the one that actually sticks) If you create 100 Duck objects, Java does not create 100 static variables. There is exactly one static variable, sitting in class memory, not object memory. class Duck { static int duckCount = 0; Duck() { duckCount++; } } Every new Duck() hits the same duckCount . Key rules (non-negotiable) Static variables are created when the class is loaded They live as long as the class is in memory Accessed using: ClassName.variable ✅ (correct) object.variable ❌ (allowed but misleading — don’t do it) Classic use cases Counters (number of objects created) Constants ( static final ) Configuration values Shared caches Static Methods — behavior without an object A static method does not need an object to run. Math.random(); No new Math() anywhere. That’s the point. Why static methods exist Because sometimes: behavior does not depend on object state creating objects would be wasteful or meaningless The iron law of static methods A static method can directly access ONLY static variables and static methods. Why? Because static methods run without knowing which object exists. This fails: class Test { int x = 10; static void go() { System.out.println(x); // ❌ compile-time error } } This works: static int y = 20; static void go() { System.out.println(y); // ✅ } Static vs Instance — memory truth table Feature Static Instance Belongs to Class Object Copies created One per class One per object Accessed via Class name Object reference Can access instance data ❌ ✅ Created when Class loads Object created static final — constants done right class MathUtils { static final double PI = 3.14159; } Rules: Must be initialized once Value cannot change Naming convention: ALL_CAPS This is how Java replaces C-style macros — safely. Static imports — power tool, use sparingly import static java.lang.Math.*; Now: sqrt(25); random(); Opinionated truth: Static imports are fine for constants and math, terrible when they hide where things come from. Exam & interview traps (Head First loves these) Static methods cannot be overridden, only hidden main() is static → JVM calls it without creating an object Static variables are shared → changes affect all objects Accessing static members via object reference compiles, but is bad design 🔥 MCQ Question Bank (Tough, exam-grade) How many copies of a static variable exist per class? A. One per object B. One per thread C. One per class D. One per method call Answer: C Explanation: Static variables are class-level, not object-level. Which access is preferred? A. obj.staticVar B. ClassName.staticVar C. Both are identical in meaning and style D. Static variables cannot be accessed directly Answer: B Explanation: Accessing via class name reflects true ownership. What happens if a static variable is modified by one object? A. Only that object sees the change B. JVM creates a copy for that object C. All objects see the change D. Compile-time error Answer: C Explanation: There is only one shared copy. Which method can access instance variables directly? A. static B. final C. abstract D. non-static Answer: D Explanation: Instance methods run with an object context. Why is main() static? A. For speed B. To avoid memory leaks C. JVM needs to call it without creating an object D. Because it returns void Answer: C Which statement is TRUE? A. Static methods can override instance methods B. Instance methods can override static methods C. Static methods cannot be overridden D. Static methods are polymorphic Answer: C Explanation: Static methods are resolved at compile time. Where do static variables live? A. Stack B. Heap (inside objects) C. Method area / class memory D. CPU registers Answer: C What happens if you access a static variable via an object reference? A. Runtime exception B. Compile-time error C. JVM redirects to class-level variable D. A new copy is created Answer: C Explanation: Legal but misleading. Can a static method use this ? A. Yes B. No C. Only in constructors D. Only with final variables Answer: B Explanation: No object context exists. Which is the best use of static final ? A. Loop counters B. Constants C. Temporary values D. Object state Answer: B Can a non static method call a static variable in Java? Static variables are class variable not instance or local variable . that is why we can use static variable in non static method also. and static variables are not per object . ... Static members are not instance members , these are shared by class , so basically any instance method can access these static members Why we Cannot call non static method from static method?(Without creating object) You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class. ... static method can call directly to the another static method in the same class.you dont need to create object of class Can you call a static method from a non static method? Because all static things are not related to any object, but they are related to a class. So all objects of same class will access the same static methods. ... You can call static methods without creating any object of a class, but that is not the case with non static methodsō Is it possible static class in Java? The answer is both "YES" and "NO". Let us see. Java comes with two types of classes – top-level classes and inner classes (also known as nested classes). A top-level class cannot be static where as a nested class can be static. Conditional Statements (if, else, switch) int i = 5 ; switch ( i ) { case 1 : System. out .println( "Sunday" ) ; case 2 : System. out .println( "Monday" ) ; case 3 : System. out .println( "Tuesday" ) ; case 4 : System. out .println( "Wednesday" ) ; case 5 : System. out .println( "Friday" ) ; default : System. out .println( "Thursday" ) Looping Statements (for, while, do while) public class J_DoWhileExplained { public static void main (String[] args) { int i= 1 ; do { System. out .println( "hello" ) ; i++ ; } while (i <= 5 ) ; } } public class I_WhileExplained { public static void main (String[] args) { int i= 1 ; while (i<= 5 ) { System. out .println(i) ; i++ ; } } } Break and continue statements Break int i = 5 ; switch ( 5 ) { case 1 : System. out .println( "Sunday" ) ; case 2 : System. out .println( "Monday" ) ; case 3 : System. out .println( "Tuesday" ) ; case 4 : System. out .println( "Wednesday" ) ; case 5 : System. out .println( "Friday" ) ; break; default : System. out .println( "Thursday" ) ; Output : Friday (without break output : Friday Thursday) Continue: public class R_Continue { public static void main (String[] args) { for ( int i = 0 ; i < 10 ; i++) { if (i== 3 ) { continue; } System. out .println(i) ; } } } Write a Java program that loops from 1 to 50 and prints each number, but skips multiples of 3 using continue and stops the loop completely when a number divisible by both 7 and 5 is encountered using break . 1st part only skips multiples of 3 : public class Main { public static void main(String[] args) { int i=1; for(i=1;i<=50;i++) { if(i%3==0) { continue; } System.out.println(i); } } } full program skips multiples of 3 and if div by 5 and 7 public class Main { public static void main(String[] args) { int i=1; for(i=1;i<=50;i++) { if(i%3==0) { continue; } if(i%5==0 && i%7==0) { break; } System.out.println(i); } } } Write a Java program that loops from 1 to 100 and: skips all numbers that are divisible by 4 using continue stops the loop completely when it encounters the first number divisible by both 6 and 9 using break prints all other numbers normally public class Main { public static void main(String[] args) { for(int i=1;i<=100;i++) { if(i%4==0) { continue; } if(i%6==0 && i%9==0) { break; } System.out.println(i); } } } Write a Java program that iterates over each character of a given String and: skips all vowels using continue stops the loop completely when the character 'z' is encountered using break prints all other characters normally public class Main { public static void main(String[] args) { String s="abcdefghijklmnopqrstuzvwxy"; for (int i=0;i { char ch=s.charAt(i); if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') { continue; } if(ch=='z') { break; } System.out.println(ch); } } } Enhanced for loop ArrayList al= new ArrayList() ; al.add( "wasim" ) ; al.add( "xyz" ) ; al.add( "Daniyal" ) ; al.add( "Noida" ) ; al.add( "Delhi" ) ; //type iter for (String s : al) { System. out .println(s) ; } What is the enhanced for loop and when is it used? List fruits = new ArrayList<>(); fruits.add( "Apple" ); fruits.add( "Banana" ); fruits.add( "Cherry" ); for (String fruit : fruits) { System.out.println(fruit); } String fruit: Declares a variable fruit of type String that will hold each element of the list fruits during the iteration. Runtime Polymorphism or Dynamic method dispatc h class Parent { public void M ( int x) { System.out.println( "method" ); } } class Child extends Parent { public void M (string y) { System.out.println( "method over ridden" ); } } public class Simple { public static void main (String args[]){ Parent p= new Child ( 10 );. }} an overridden version of the child method is called. When an overridden method is called through a superclass reference, Java determines which version(superclass/subclasses) of that method is to be executed based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. Compile time Polymorphism (or Static polymorphism) class SimpleCalculator { int add ( int a, int b) { return a+b; } int add ( int a, int b, int c) { return a+b+c; } } public class Demo { public static void main (String args[]) { SimpleCalculator obj = new SimpleCalculator(); System.out.println(obj.add( 10 , 20 )); System.out.println(obj.add( 10 , 20 , 30 )); } } Method overloading is one of the way java supports static polymorphism. Here we have two definitions of the same method add() which add method would be called is determined by the parameter list at the compile time. That is the reason this is also known as compile time polymorphism. Encapsulation(Private Variable+getter setter) Encapsulation is one of the four fundamental OOP (Object-Oriented Programming) concepts. It refers to the bundling of data (variables) and methods (functions) that operate on the data into a single unit or class. Encapsulation restricts direct access to some of the object's components, which is a means of preventing accidental interference and misuse of the data. The data can only be accessed through well-defined interfaces (getter and setter methods). In Java, encapsulation is achieved by: 1. Declaring the variables of a class as private. 2. Providing public getter and setter methods to modify and view the variables' values. public class W_EncapsulationDemo { public static void main (String[] args) { W_EncapsulationDemo obj= new W_EncapsulationDemo() ; obj.setPAN( "ABCD1234" ) ; obj.setSal( 12309876 ) ; System. out .println(obj.getPAN()) ; System. out .println(obj.getSal()) ; } private String PAN ; private int sal ; //alt+"insert" shortcut to add set and get method public String getPAN () { return PAN ; } public int getSal () { return sal ; } public void setPAN (String PAN) { this . PAN = PAN ; } public void setSal ( int sal) { if (sal > 0 ) { this . sal = sal ; //this.sal -> refers to instance variable id refers to the local variable } else { System. out .println( "sal must be positive." ) ; } } } Perfect. Let’s do this end-to-end, slowly, cleanly, and in the exact order you should teach. Assume the student knows basic Java syntax only. Nothing else. We will go from fields → getters/setters → inheritance → override → polymorphism → output. No gaps. No assumptions. --- STEP 1: Create the base class (Teacher) Goal Store common data and behavior. package teacher; public class Teacher { // Step 1.1: Declare variables (data) private String name; protected int factId; } Explain private → data hiding protected → child class can access This is encapsulation foundation --- STEP 2: Generate getters and setters (Eclipse shortcut) Action 1. Cursor inside class 2. Press Alt + Shift + S 3. Press R 4. Select name, factId 5. Click Generate Result (Eclipse writes this) public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFactId() { return factId; } public void setFactId(int factId) { this.factId = factId; } Explain Getters → read data Setters → modify data this.name → object variable This is standard Java practice --- STEP 3: Add constructor to Teacher Why? So objects start with valid data. public Teacher(String name, int factId) { this.name = name; this.factId = factId; } Explain Constructor runs at object creation Ensures object is not half-empty --- STEP 4: Add display() method in Teacher public void display() { System.out.println("Name: " + getName()); System.out.println("ID: " + factId); } Explain Uses getName() instead of name Shows encapsulation in action This method will be overridden later --- STEP 5: Create child class (HOD) Goal Specialized Teacher with extra behavior. package admin; import teacher.Teacher; public class HOD extends Teacher { private String dateOfAppointment; } Explain extends Teacher → IS-A relationship HOD inherits everything non-private --- STEP 6: Create constructor in HOD public HOD(String name, int factId, String dateOfAppointment) { super(name, factId); // calls Teacher constructor this.dateOfAppointment = dateOfAppointment; } Explain super() initializes parent part Child adds its own data Object is built top-down --- STEP 7: Override display() in HOD @Override public void display() { System.out.println("Name: " + getName()); System.out.println("Date of Appointment: " + dateOfAppointment); } Explain Same method name, same signature Different implementation This sets up runtime polymorphism --- STEP 8: Create Main class This is where everything connects. import teacher.Teacher; import admin.HOD; public class Main { public static void main(String[] args) { // Step 8.1: Parent reference, child object Teacher t = new HOD("Wasim", 101, "01-Jan-2024"); // Step 8.2: Call method t.display(); } } --- STEP 9: What happens internally (VERY IMPORTANT) Line 1 Teacher t = new HOD(...); Reference type → Teacher Object type → HOD Allowed because: HOD IS-A Teacher --- Line 2 t.display(); Java decides at runtime: Which object? → HOD So which method? → HOD.display() Even though reference is Teacher. This is polymorphism. --- STEP 10: Output (proof) Name: Wasim Date of Appointment: 01-Jan-2024 Explain Teacher’s display() is ignored HOD’s version runs Decision made at runtime --- STEP 11: Where getName() came from (final clarity) Defined in Teacher Inherited by HOD Used inside overridden method Not polymorphism, just inheritance --- STEP 12: One clean mental chain (teach this) 1. Encapsulation → private fields + getters/setters 2. Inheritance → extends 3. Method overriding → same method, new behavior 4. Polymorphism → parent reference, child object 5. Runtime binding → object decides method --- STEP 13: One-line exam/interview summary > Polymorphism allows a parent reference to call a child’s overridden method at runtime, while shared data is accessed using inherited getters. --- If you want, next we can: Break this into MCQs Add UML diagram Show what breaks if rules are violated Convert this into real-world analogy Add casting example (safe vs unsafe) This is now a complete, classroom-ready, end-to-end explanation. Custom exceptions Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java. package Java_set2 ; class CustomAgeException extends Exception { public CustomAgeException (String message) { super (message) ; } } public class A_CustomException { private int age ; public int getAge () { return age ; } public void setAge ( int age) { try { if (age < 18 ) { // Throwing custom exception if age is less than 18 throw new CustomAgeException( "Not a good age to vote" ) ; } this . age = age ; } catch (CustomAgeException e) { // Handling custom exception e.printStackTrace() ; } } public static void main (String[] args){ A_CustomException obj = new A_CustomException() ; obj.setAge( 18 ) ; obj.getAge() ; System. out .println(obj.getAge()) ; } } Using throw To prevent this compile time error we can handle the exception in two ways: 1 . By using try catch 2 . By using throws keyword class tst { public static void main (String[] args) throws InterruptedException { Thread.sleep( 10000 ); System.out.println( "Hello Geeks" ); } } What is the difference between a class and an object? A class is a blueprint or template for creating objects. It defines a type by bundling data (attributes) and methods (functions) that operate on the data An object is an instance of a class. It is a concrete entity based on the class blueprint, with actual values assigned to its attributes. Objects interact with one another using methods defined in their class. Explain the 'this' keyword. this . sal = sal ; //this.sal -> refers to instance variable sal refers to the local variable How do checked exceptions differ from unchecked exceptions? Unchecked exceptions are not checked at compile-time rather they are checked at runtime.exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Checked exceptions in Java are exceptions that are checked at compile-time. The Java compiler requires that methods that can throw checked exceptions either handle them with a try-catch block or declare them using the throws keyword in the method signature What is the purpose of the finally block? The finally block in Java is used to execute important code regardless of whether an exception is thrown or not. It's typically used for: 1. Resource cleanup: Closing files, sockets, or database connections to free up resources. 2. Releasing locks: Ensuring that locks are released to avoid deadlock situations. 3. Logging: Logging exceptions or important events. 4. Cleanup tasks: Performing any necessary cleanup tasks, like deleting temporary files. The finally block is executed: - After the try block completes normally - After the catch block completes - Even if a return statement is executed in the try or catch block - Even if a new exception is thrown in the catch block The finally block is not executed only if: - The JVM crashes or terminates abruptly - A System.exit() call is made StringBuilder vs. StringBuffer In Java, both StringBuilder and StringBuffer are used to represent a mutable sequence of characters. However, there are key differences between them: StringBuilder - Faster and more efficient - Not thread-safe (cannot be used in multithreaded environments) - Methods are not synchronised StringBuffer - Thread-safe (can be used in multithreaded environments) - Slower than StringBuilder due to synchronization overhead - Methods are synchronized You’ve got the theory right. Now let’s prove it with code, not vibes. Below are clean, minimal Java examples with inline comments that explain exactly what’s happening and why it matters . No fluff. 🔹 Example 1: StringBuilder (Fast, NOT thread-safe) class StringBuilderExample { public static void main(String[] args) { // StringBuilder is mutable and NOT synchronized // It is fast but unsafe in multithreaded scenarios StringBuilder sb = new StringBuilder(); // First thread appending text Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { sb.append("A"); // No lock, direct modification } }); // Second thread appending text Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { sb.append("B"); // Race condition can occur } }); t1.start(); t2.start(); // Wait for both threads to finish try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } // Expected length = 2000 // Actual length MAY BE LESS due to data corruption System.out.println("Length using StringBuilder: " + sb.length()); } } 🔍 What’s happening here? Both threads modify the same object at the same time No synchronization = race condition Result is unpredictable Fast, but dangerous in multithreading 👉 Strong opinion: Using StringBuilder in multithreading without external synchronization is a bug, not an optimization. 🔹 Example 2: StringBuffer (Thread-safe, Slower) class StringBufferExample { public static void main(String[] args) { // StringBuffer is mutable AND synchronized // Safe for multithreaded use StringBuffer sb = new StringBuffer(); // First thread appending text Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { sb.append("A"); // synchronized method (lock acquired) } }); // Second thread appending text Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { sb.append("B"); // synchronized method (lock acquired) } }); t1.start(); t2.start(); // Wait for both threads to finish try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } // Always correct: 2000 System.out.println("Length using StringBuffer: " + sb.length()); } } 🔍 What’s happening here? append() is synchronized Only one thread enters at a time No data corruption Slightly slower due to locking 👉 Strong opinion: Correct + slow beats fast + wrong every single time in production systems. 🔹 Key Difference Shown in One Line // StringBuilder append (NOT synchronized) public StringBuilder append(String str) // StringBuffer append (synchronized) public synchronized StringBuffer append(String str) That single keyword synchronized changes everything. 🔹 When to Use What (Rule You Should Memorize) Single-threaded code → StringBuilder ✅ Multi-threaded shared object → StringBuffer ✅ Modern Java + multithreading → StringBuilder + synchronized or StringBuilder + Lock (preferred) Both are worth knowing. Defining and Implementing Interfaces Finally this method will return a big string made of count occurrences of the word, separated by the separator string. Test case 1: repeatSeparator("This", "X", 3) → Expected O/P : "ThisXThisXThis" Test case 2: repeatSeparator("This", "And", 2) → Expected O/P :"ThisAndThis" Test case 3: repeatSeparator("This", "And", 1) → Expected O/P : "This" Inheritance in java is a mechanism in which one object acquires all the properties and behaviours of the parent object. On the basis of class, there can be three types of inheritance in java: single(A>B), multilevel(A>B>C) and hierarchical(A>B,C). Good. This is the spine of Object-Oriented Programming. If this clicks, half of Java becomes obvious instead of mystical. I’ll go concept → simple Java code, clean and slow, no ceremony. Revision 1️⃣ Inheritance What is Inheritance? Inheritance means reusing existing code by creating a new class from an existing class. Parent class → base / superclass Child class → derived / subclass Relationship → IS-A Example idea: A Car is a Vehicle Why Inheritance exists Avoid code duplication Centralize common behavior Enable polymorphism How Java implements Inheritance Java uses the extends keyword. // Parent class class Vehicle { int speed = 60; void move() { System.out.println("Vehicle is moving"); } } // Child class class Car extends Vehicle { void showSpeed() { System.out.println("Speed is " + speed); } } public class Main { public static void main(String[] args) { Car c = new Car(); c.move(); // inherited method c.showSpeed(); // child method } } What happens here Car automatically gets speed and move() No copy-paste This is single inheritance 2️⃣ Types of Inheritance in Java 1. Single Inheritance class A { } class B extends A { } 2. Multilevel Inheritance class A { } class B extends A { } class C extends B { } 3. Hierarchical Inheritance class A { } class B extends A { } class C extends A { } ❌ Multiple inheritance using classes is NOT allowed in Java (Java avoids ambiguity) 4️⃣ super keyword super refers to the immediate parent class object. Think of it as: “Hey compiler, go talk to my parent.” It is mainly used for three things: Accessing parent class variables Calling parent class methods Calling parent class constructors 1️⃣ super with Constructor (your example) Code class Person { Person(String name) { System.out.println("Person name: " + name); } } class Student extends Person { Student() { super("Wasim"); // calls parent constructor System.out.println("Student constructor"); } } public class Main { public static void main(String[] args) { new Student(); } } Output Person name: Wasim Student constructor What ACTUALLY happens (step-by-step) new Student() is called. Student constructor starts. First line is super("Wasim") . This calls the constructor of Person Passes "Wasim" to it Person constructor prints: Person name: Wasim Control comes back to Student constructor. Student constructor is printed. 👉 Parent constructor always runs BEFORE child constructor. No exception. Golden Rules of super with Constructor (EXAM FAVORITE) super() must be the first statement inside a constructor If you don’t write super() , Java inserts it automatically If parent has only parameterized constructor, you must call super(args) You cannot use super() inside methods Strong opinion: If you forget this rule in interviews, it screams weak OOP foundation . 2️⃣ super with Variables Example class Person { String role = "Human"; } class Student extends Person { String role = "Student"; void printRole() { System.out.println(role); // Student System.out.println(super.role); // Human } } Output Student Human 👉 Use super.variable when child and parent have same variable name. 3️⃣ super with Methods Example class Person { void work() { System.out.println("Person works"); } } class Student extends Person { void work() { System.out.println("Student studies"); super.work(); } void callParentWork() { } } Output Person works 👉 super.method() is used to call overridden parent method. One-Line Exam Answers (Save These) super refers to immediate parent class object Used to access parent variables, methods, constructors super() must be first statement in constructor Parent constructor executes before child constructor If you want, next we can compare super vs this side-by-side, or I can throw MCQs + tricky output questions—the kind examiners love and students fear. Rule: Parent constructor always runs first 4️⃣ Polymorphism What is Polymorphism? Polymorphism means many forms. In Java: Same method name behaves differently based on object type. This works only with inheritance. 5️⃣ Types of Polymorphism in Java 1. Static Polymorphism (Compile-time) Achieved using method overloading class MathUtil { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } Decision made at compile time. 2. Dynamic Polymorphism (Runtime) Achieved using method overriding 6️⃣ Method Overriding (core concept) Rules: Same method name Same parameters Parent-child relationship Runtime decision class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // parent reference, child object a.sound(); // runtime decision } } Output Dog barks This line is the magic: Animal a = new Dog(); Java decides at runtime which method to call. 7️⃣ Abstract Class What is an Abstract Class? An abstract class: Cannot be instantiated May contain abstract (incomplete) methods Forces child classes to implement behavior Abstract class example abstract class Shape { abstract void draw(); void info() { System.out.println("This is a shape"); } } class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); } } public class Main { public static void main(String[] args) { Shape s = new Circle(); s.draw(); s.info(); } } Key rule: Abstract methods must be implemented by child class 8️⃣ Interface What is an Interface? An interface is a 100% contract. Only abstract methods (Java 7) Supports multiple inheritance Uses implements Interface example interface Payment { void pay(); } class CardPayment implements Payment { public void pay() { System.out.println("Payment done using Card"); } } public class Main { public static void main(String[] args) { Payment p = new CardPayment(); p.pay(); } } 9️⃣ Abstract Class vs Interface (simple truth) Feature Abstract Class Interface Inheritance Single Multiple Methods Abstract + concrete Abstract only Variables Instance public static final Keyword extends implements 🧠 One mental model (very important) Inheritance → reuse Polymorphism → flexibility Overloading → compile time Overriding → runtime Abstract class → partial design Interface → full contract Final strong opinion (remember this) Java OOP is not about syntax. It’s about who controls behavior at runtime. In java programming, multiple(A,B>C) and hybrid inheritance is supported through interface only. Interface Syntax [visibility] interface InterfaceName [ extends other interfaces ] { constant declarations abstract method declarations (); / Note the semicolon // Interface methods are public, abstract and never final. // Think of them as prototypes only; no implementations are allowed} interface Student { int age= 25 ; ------->C O M P I L E R void method (); } interface Student { public static final int age= 25 ; public abstract void mrthod (); } Abstract Classes vs. Interfaces Type of methods: Interface can have only abstract methods. Abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also. Type of variables: Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. Implementation: Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class. Inheritance vs Abstraction: A Java interface can be implemented using keyword “implements” and abstract class can be extended using keyword “extends”. Multiple implementation: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc. Interface : Why Public static and final??? public: for the accessibility across all the classes, just like the methods present in the interface static: as an interface cannot have an object, the interfaceName.variableName can be used to reference it or directly the variableName in the class implementing it. final: to make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur Default and Static Methods in Interfaces Prior to JDK 8, interfaces could not define implementation. We can now add default implementation for interface methods. This default implementation has special use and does not affect the intention behind interfaces. public class Simple implements InterFaceS { public static void main (String args[]){ Simple s= new Simple(); s.display(); }} interface InterFaceS { int x= 54 ; default void display () { System.out.println( "hello" ); } } concise list differentiating what an abstract class can/can't have versus what an interface can/can't have, focusing on methods and variables: Abstract Class: - Can Have: - Abstract methods (methods without implementation, declared with `abstract` keyword). - Concrete methods (methods with implementation). - Fields (instance variables). - Constructors. - Static methods. ________________________ Interface(can/cant have): - Can Have: - Constant variables (static final variables). - Default methods (methods with implementation using the `default` keyword). - Static methods (methods associated with the interface, not instance methods). - Nested types (static classes and interfaces). - Constant expressions (since Java 9). - Default methods from `Object` class (since Java 8). - Can't Have: - Instance fields (non-static variables). - Constructors. - Concrete methods (methods with implementation until Java 8). Multiple Inheritance in Java public interface MultipleInheritance1 { void speed () ; } public interface MultipleInheritance2 { void distance () ; } public class ClassImplemntsMultipleInheritance implements MultipleInheritance1 , MultipleInheritance2{ @Override public void speed () { System. out .println( "ClassImplemntsMultipleInheritance1" ) ; } @Override public void distance () { System. out .println( "ClassImplemntsMultipleInheritance2" ) ; } public static void main (String[] args) { ClassImplemntsMultipleInheritance obj= new ClassImplemntsMultipleInheritance() ; obj.distance() ; obj.speed() ; } } When would you use a default method in an interface? Default methods allow interfaces to provide a default implementation of a method, which can be optionally overridden by classes that implement the interface. This flexibility is particularly useful when extending interfaces without breaking existing implementations. — Creating and Managing Threads A thread in Java is a lightweight process that allows multiple tasks to run concurrently within a single process. Java provides built-in support for multithreading through the java.lang.Thread class and the java.lang.Runnable interface. _ If you write a simple program to print "Hello", only the main thread is involved. Creating and Managing Threads To create and manage threads, you can either extend the Thread class or implement the Runnable interface. Extending the Thread Class When you extend the Thread class, you need to override the run method. class MyThread extends Thread { public void run () { System.out.println( "Hello from MyThread!" ); } } public class ThreadExample { public static void main (String[] args) { MyThread t1 = new MyThread(); t1.start(); // This starts the new thread, which calls the run() method } } Synchronisation - multiple program accessing the thread Consider a bank account where multiple threads are trying to deposit money into the account. Without synchronisation, the balance could become inconsistent due to race conditions. Set 2- Logical(11/11/25) Write a program to find the largest of three numbers using if➡ else. public class S_LargestOfThree { public static void main (String[] args) { int x= 2 ; int y= 5 ; int z= 3 ; int largest ; if (x>=y && x>=z) { largest=x ; } if (y>=x && y>=z) { largest=y ; } else { largest=z ; } System. out .println( "The Largest is " +largest) ; Implement a program to print the first ten numbers using a for loop. for ( int i = 0 ; i <= 10 ; i++) { System. out .println(i) ; } String Manipulation public class StringManipulation { public static void main (String[] args) { // Initial string String original = "Hello, World!" ; // Substring String substring = original.substring( 7 , 12 ); System.out.println( "Substring: " + substring); // Changing case String upperCase = original.toUpperCase(); System.out.println( "Upper case: " + upperCase); String lowerCase = original.toLowerCase(); System.out.println( "Lower case: " + lowerCase); // Replacing characters String replaced = original.replace( 'o' , 'a' ); System.out.println( "Replace 'o' with 'a': " + replaced); // Removing whitespace String whitespace = " Lots of spaces " ; String trimmed = whitespace.trim(); System.out.println( "Trimmed: '" + trimmed + "'" ); // Splitting a string String csv = "apple,banana,cherry" ; String[] fruits = csv.split( "," ); System.out.println( "Split: " ); for (String fruit : fruits) { System.out.println(fruit); } // Checking if a string contains a substring boolean contains = original.contains( "World" ); System.out.println( "Contains 'World': " + contains); // String length int length = original.length(); System.out.println( "Length: " + length); // Character at a specific index char charAt = original.charAt( 6 ); System.out.println( "Character at index 6: " + charAt); } } String vs String New public class U_StringComparisonExample { public static void main (String[] args) { String str1 = "Hello" ; String str2 = new String( "Hello" ) ; //When you create a string using the new keyword, it creates a new object on the heap String str3 = "Hello" ; //Both str1 and str3 refer to the same object because they are initialized with the same literal. // Using == for reference equality //The == operator checks if two references point to the same object. System. out .println( "Using == for reference equality:" ) ; System. out .println( "str1 == str2: " + (str1 == str2)) ; // false System. out .println( "str1 == str3: " + (str1 == str3)) ; // true // Using equals for content equality //The equals method checks if two objects have the same content. System. out .println( "Using equals for content equality:" ) ; System. out .println( "str1.equals(str2): " + str1.equals(str2)) ; // true System. out .println( "str1.equals(str3): " + str1.equals(str3)) ; // true /* String str1 = "Hello"; This creates a string "Hello" and stores it in the string pool. String str3 = "Hello"; Since "Hello" is already in the string pool, str3 refers to the same object as str1. String str2 = new String("Hello"); This creates a new string object in memory, separate from the string pool. */ } } Write a program to reverse a string public class ReverseAString { public static void main (String[] args) { String s= "wasim" ; String rev= "" ; for ( int i = s.length()- 1 ; i >= 0 ; i--) { rev=rev+s.charAt(i) ; } System. out .println(rev) ; } } Unique String public class UniqueStringArray { public static void main (String[] args) { String s[]={ "wasim" , "wasim" , "sudhakar" , "sudhakar" } ; HashSet hs= new HashSet<>() ; for ( int i= 0 ; i< s. length ; i++) { hs.add(s[i]) ; } System. out .print(hs + "," ) ; } } Unique Character class Codechef { public static void main (String[] args) { String s="aaaaabbbbbbcccrrrrrrrrc"; char[] ch=s.toCharArray(); HashSet hs= new HashSet<>(); for (int i=0;i { hs.add(ch[i]); } System.out.println(hs); } } Write a program to demonstrate the immutability of String objects. package j1_javaBasics ; public class U_StringComparisonExample { public static void main (String[] args) { String str1 = "Hello" ; String str2 = new String( "Hello" ) ; //When you create a string using the new keyword, it creates a new object on the heap String str3 = "Hello" ; //Both str1 and str3 refer to the same object because they are initialized with the same literal. // Using == for reference equality //The == operator checks if two references point to the same object. System. out .println( "Using == for reference equality:" ) ; System. out .println( "str1 == str2: " + (str1 == str2)) ; // false System. out .println( "str1 == str3: " + (str1 == str3)) ; // true // Using equals for content equality //The equals method checks if two objects have the same content. System. out .println( " \n Using equals for content equality:" ) ; System. out .println( "str1.equals(str2): " + str1.equals(str2)) ; // true System. out .println( "str1.equals(str3): " + str1.equals(str3)) ; // true / String str1 = "Hello"; This creates a string "Hello" and stores it in the string pool. String str3 = "Hello"; Since "Hello" is already in the string pool, str3 refers to the same object as str1. String str2 = new String("Hello"); This creates a new string object in memory, separate from the string pool. / } } Implement a program to concatenate multiple strings using StringBuilder. StringBuffer sb= new StringBuffer( "Wasim" ) ; System. out .println(sb.capacity()) ; sb.append( " Ansari" ) ; System. out .println(sb.capacity()) ; System. out .println(sb) ; System. out .println(sb.capacity()) ; String Trim index public class Z23_Subtring_trim_index { public static void main (String[] args) { String s= "wasim(guest)" ; int startIndex=s.indexOf( '(' ) ; int endIndex=s.indexOf( ')' ) ; String output=s.substring(startIndex+ 1 , endIndex) ; System. out .println(output) ; String outs=s.trim().substring( 0 , startIndex) ; System. out .println(outs) ; } } String Special Character Remove String s1= "wasim!@#$123" ; String s2=s1.replaceAll( "[^a-zA-Z\\s]" ); //Read this as ^not a-z A_Z for blank-> \\s char[] ch=s1.toCharArray(); for(int i=0;i{ System.out.println(ch); } method 2 public class Main { public static void main(String[] args) { String s="wasim!@#$123"; for(int i=0; i{ char ch=s.charAt(i); if(!Character. isLetterOrDigit (ch)) { continue; } System.out.print(ch); } } Find the Second Largest Number in an Array public class SecondLargestArrayNumber { public static void main (String[] args) { int a[] = { 2 , 6 , 4 , 7 , 3 , 12 , 3 , 4 , 22 , 34 , 31 , 8 , 9 , 23 } ; Arrays. sort (a) ; int SecondLargest=a[a. length - 2 ] ; System. out .println( "The Second Largest Number is:" ) ; System. out .println(SecondLargest) ; } } Remove duplicate words from sentence public class H_RemoveDuplicateWordsFromSentence { public static void main (String[] args) { String s = "my name is is wasim wasim" ; String[] words = s.split( " " ) ; // Using a LinkedHashSet to store unique words Set uniqueWords = new LinkedHashSet<>(Arrays. asList (words)) ; System. out .println(uniqueWords) ; System. out .println(String. join ( " " , uniqueWords)) ; } } Swap Strings public class J_SwapStrings { public static void main (String[] args) { String a= "Hello" ; String b= "World" ; a= a + b ; b=a.substring( 0 , a.length()-b.length()) ; System. out .println( "b is " +b) ; a=a.substring(b.length()) ; System. out .println( "a is " +a) ; } } Reverse an Array Find the Duplicate Elements // Array with duplicate elements int a[] = { 1 , 2 , 1 , 3 , 3 , 4 , 4 , 5 } ; // HashSet to store non-duplicate elements Set nonDuplicateSet = new HashSet<>() ; // Iterate through the array and add elements to the HashSet for ( int i = 0 ; i < a. length ; i++) { nonDuplicateSet.add(a[i]) ; // HashSet automatically handles duplicates } // Print non-duplicate elements from the HashSet System. out .print( "Non-duplicate elements: " ) ; for (Integer i : nonDuplicateSet) { System. out .print(i + " " ) ; // Print each non-duplicate element } Find common an Array Write a Java Program to swap two numbers without using the third variable. int n= 12 ; int x=n% 10 ; //2 int y=n/ 10 ; //3 System. out .println(n% 10 ) ; System. out .println(n/ 10 ) ; System. out .println( "the swapped number is " + x% 10 +y ) ; Write a Java Program to count the number of words in a string using HashMap. String s= "mywordscount" ; System. out .println(s.length()) ; Write a Java Program to count the number of words in a string with using length() method public class Main { public static void main ( String [] args ) { //System.out.println("Hello, World!"); String s = "wasimdswdsdsdsdfgcghcghgh" ; int count = 0 ; char [] a = s . toCharArray (); for ( char x : a ) { count ++; } System . out . println ( count ); } } Fibonacci Series public class Q_Fibonacci { public static void main (String[] args) { int n = 10 ; // Number of terms int a = 0 , b = 1 ; System. out .print( "Fibonacci Series: " + a + " " + b) ; for ( int i = 2 ; i < n ; i++) { int next = a + b ; System. out .print( " " + next) ; a = b ; b = next ; } } } String Buffer vs Builder package j1_javaBasics ; public class V_StringvsStringBuffer { public static void main (String[] args) { // Immutable String Example String original = "Hello" ; String modified = original.concat( " World" ) ; // Printing modified and original strings System. out .println( "Modified String (String): " + modified) ; System. out .println( "Original String (String): " + original) ; /* * In this example: * - original is "Hello". * - modified is a new string "Hello World" created by concatenating " World" to original. * - original remains unchanged after concatenation. * * This demonstrates that strings in Java are immutable, meaning: * - Once a string is created, its content cannot be changed. * - Any operation that appears to modify a string actually creates a new string object. */ // Mutable StringBuffer Example StringBuffer buffer = new StringBuffer( "Hello" ) ; buffer.append( " World" ) ; // Printing StringBuffer content System. out .println( "Modified String (StringBuffer): " + buffer) ; /* * StringBuffer (or StringBuilder) in Java: * - Unlike String, StringBuffer and StringBuilder are mutable. * - They can be modified in-place without creating new objects. * - append() method in StringBuffer adds the specified string at the end of the existing content. * * For example: * - Initially, buffer is "Hello". * - After appending " World", buffer becomes "Hello World". * * StringBuffer is preferred in scenarios where frequent modifications to strings are required * because it avoids the overhead of creating new string objects. */ // Mutable StringBuilder Example StringBuilder builder = new StringBuilder( "Hello" ) ; builder.append( " World" ) ; // Printing StringBuilder content System. out .println( "Modified String (StringBuilder): " + builder) ; /* * StringBuilder in Java: * - StringBuilder is similar to StringBuffer but is not synchronized.Mutable but not synchronized. * - It is preferred in single-threaded environments for better performance. * - Like StringBuffer, StringBuilder can be modified in-place using methods like append(). * * In this example: * - Initially, builder is "Hello". * - After appending " World", builder becomes "Hello World". */ } } Prime number Swap two digits public class M_SwapNumbers_TwoDigits { public static void main (String[] args) { int n= 23 ; int x=n% 10 ; //2 int y=n/ 10 ; //3 System. out .println(n% 10 ) ; System. out .println(n/ 10 ) ; System. out .print( "the swapped number is " + x% 10 +y ) ; } } Sum of digits public class T_sumOfdidigits { public static void main (String[] args) { int digit , sum= 0 ; Scanner sc= new Scanner(System. in ) ; int number=sc.nextInt() ; while (number> 0 ) { digit=number% 10 ; sum=sum+digit ; number=number/ 10 ; } System. out .println( "the sum of digiti is " +sum) ; } } Anagram public class U_Anagram { //LISTEN and SILENT are same characters only order of characters are different public static void main (String[] args) { Scanner sc= new Scanner(System. in ) ; String s1=sc.next() ; String s2=sc.next() ; System. out .println( "Enter String 1" +s1) ; System. out .println( "Enter String 1" +s2) ; int n1=s1.length() ; int n2=s2.length() ; Arrays. sort (s1.toCharArray()) ; Arrays. sort (s2.toCharArray()) ; } } Print the character and their occurrence import java.util.HashMap ; public class StringDemo11223 { static String s = "Bangalore" ; public static void CountChar () { // Create a HashMap to store the character and its count HashMap charCountMap = new HashMap<>() ; // Iterate over each character in the string for ( int i = 0 ; i < s .length() ; i++) { char ch = s .charAt(i) ; // If the character is already in the map, increment its count if (charCountMap.containsKey(ch)) { charCountMap.put(ch , charCountMap.get(ch) + 1 ) ; } else { // If the character is not in the map, add it with a count of 1 charCountMap.put(ch , 1 ) ; } } // Print the characters and their occurrences for (HashMap.Entry entry : charCountMap.entrySet()) { System. out .println(entry.getKey() + ": " + entry.getValue()) ; } } public static void main (String[] args) { CountChar () ; } } – Set 3- Collections in java Using ArrayList Key Features of ArrayList: Dynamic resizing: Automatically grows in size when elements are added. Random access: Provides fast access to elements using their index. Maintains insertion order: Elements are stored and accessed in the order they were added. Allows duplicates: Duplicate elements are allowed in an ArrayList . Iteration in List public class C_IterationWithStream_ArrayList { public static void main (String[] args) { ArrayList fruits = new ArrayList<>() ; // Add elements fruits.add( "Apple" ) ; fruits.add( "Banana" ) ; fruits.add( "Cherry" ) ; fruits.stream().forEach(System. out ::println) ; ///or.... for (String fruit : fruits) { System. out .println(fruit) ; } } } Using HashMap Key Features of HashMap: No duplicate keys: Each key can map to at most one value. Allows null values and one null key. Not synchronised: If multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. Does not maintain insertion order: The order of keys and values can change. package AllAboutCollections ; import java.util.HashMap ; public class B_HashMap { public static void main (String[] args) { HashMap hs= new HashMap() ; //No duplicate keys: Each key can map to at most one value. hs.put( 1 , "Delhi" ) ; hs.put( 1 , "Kolkata" ) ; //will replace //Allows null values and one null key. hs.put( null, "no city" ) ; hs.put( null, "another no city" ) ; //will replace hs.put( 11 ,null ) ; //allows null values but only one null key System. out .println(hs) ; //Not synchronised: If multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. //Does not maintain insertion order: The order of keys and values can change. HashMap map = new HashMap<>() ; map.put( "One" , "1" ) ; map.put( "Two" , "2" ) ; map.put( "Three" , "3" ) ; map.put( "Four" , "4" ) ; // Print the map System. out .println(map) ; // Output could be in any order, e.g., {Three=3, One=1, Four=4, Two=2} } } Iteration in Map public class D_IterationWithStream_HashMap { public static void main (String[] args) { HashMap map= new HashMap() ; map.put( 1 , "A" ) ; map.put( 2 , "B" ) ; map.put( 3 , "C" ) ; map.put( 4 , "D" ) ; map.put( 5 , "E" ) ; map.entrySet().stream().forEach(System. out ::println) ; //or.... for (Integer i : map.keySet()) { System. out .println(i) ; } //or... for (Map.Entry entry : map.entrySet()) { System. out .println(entry.getKey() + " = " + entry.getValue()) ; } } } Map public class D_IterationWithStream_HashMap { public static void main (String[] args) { HashMap map= new HashMap() ; map.put( 1 , "A" ) ; map.put( 2 , "B" ) ; map.put( 3 , "C" ) ; map.put( 4 , "D" ) ; map.put( 5 , "E" ) ; map.entrySet().stream().forEach(System. out ::println) ; }} Merge ArrayList public class F_MergeArrayListsExample { public static void main (String[] args) { ArrayList al1 = new ArrayList<>() ; al1.add( "Apple" ) ; al1.add( "Banana" ) ; ArrayList al2 = new ArrayList<>() ; al2.add( "Cherry" ) ; al2.add( "Date" ) ; al1.addAll(al2) ; for (String s : al1) { System. out .println(s) ; } } } ArrayList synchronization ArrayList in Java is not synchronized by default.. CopyOnWriteArrayList is a concurrent collection that is thread-safe and provides better performance for read-heavy scenarios. It's part of the java.util.concurrent package. package AllAboutCollections ; import java.util.ArrayList ; import java.util.List ; import java.util.concurrent.CopyOnWriteArrayList ; public class E_CopyOnwriteDemo_ArrayList { public static void main (String[] args) { List fruits = new CopyOnWriteArrayList<>() ; // Add elements fruits.add( "Apple" ) ; fruits.add( "Banana" ) ; fruits.add( "Cherry" ) ; fruits.stream().forEach(System. out ::println) ; } } Array list in automation public class Q_ListinAutomation { public static void main (String[] args) { WebDriver driver = new ChromeDriver() ; driver.manage().timeouts().implicitlyWait( 10 , TimeUnit. SECONDS ) ; driver.get( "https://rahulshettyacademy.com/seleniumPractise/#/offers" ) ; List tablerows=driver.findElements(By.xpath("//table/tbody/tr")); for (WebElement iter:tablerows) { List column= iter .findElements(By. xpath ( " td " )) ; String get_value=column.get( 2 ).getText() ; System. out .println(get_value) ; } } } ➡️ "If you have two ArrayLists, AL1 and AL2, how can you merge them into a third ArrayList?" package AllAboutCollections ; import java.util.ArrayList ; public class F_MergeArrayListsExample { public static void main (String[] args) { ArrayList al1 = new ArrayList<>() ; al1.add( "Apple" ) ; al1.add( "Banana" ) ; ArrayList al2 = new ArrayList<>() ; al2.add( "Cherry" ) ; al2.add( "Date" ) ; al1.addAll(al2) ; for (String s : al1) { System. out .println(s) ; } } } How do ArrayList and HashMap store elements? Use when you need a resizable array with ordered elements. -> ArrayList Use when you need a fast, unordered collection of key-value pairs. -> HashMap Collection APIs – Set and HashtableUsing Set Interface Hash Set Does not allows duplicates Hash Set Does not maintain order of insertion -> instead use LinkedHashSet Hash Set Does not prints in auto sorted order-> instead use TreeSet package AllAboutCollections ; import java.util.HashSet ; import java.util.Set ; public class G_HashSetExample { public static void main (String[] args) { Set hashSet = new HashSet<>() ; hashSet.add( "Apple" ) ; hashSet.add( "Banana" ) ; hashSet.add( "Cherry" ) ; // No Duplicates: Set does not allow duplicate elements. hashSet.add( "Apple" ) ; // HashSet: No guaranteed order. for (String s : hashSet) { System. out .println(hashSet) ; } } } Hash Set public class G_HashSetExample { public static void main (String[] args) { Set hashSet = new HashSet<>() ; hashSet.add( "Apple" ) ; hashSet.add( "Banana" ) ; hashSet.add( "Cherry" ) ; // No Duplicates: Set does not allow duplicate elements. hashSet.add( "Apple" ) ; // HashSet: No guaranteed order. for (String s : hashSet) { System. out .println(hashSet) ; } } //output - [Apple, Cherry, Banana] and not ABC Linked Hash Set package AllAboutCollections ; import java.util.HashSet ; import java.util.LinkedHashSet ; import java.util.Set ; public class H_LinkedHashSet_maitainsorder { public static void main (String[] args) { //Set LinkhashSet=new HashSet<>(); Set LinkhashSet= new LinkedHashSet<>() ; LinkhashSet.add( "Apple" ) ; LinkhashSet.add( "Banana" ) ; LinkhashSet.add( "Cherry" ) ; //LinkedHashSet: Maintains insertion order LinkhashSet.stream().forEach(System. out ::println) ; } } TreeSet package AllAboutCollections ; import java.util.Set ; import java.util.TreeSet ; public class I_TreeSet { public static void main (String[] args) { //TreeSet: Sorted order. Set ts= new TreeSet<>() ; ts.add( 3 ) ; ts.add( 1 ) ; ts.add( 4 ) ; ts.add( 5 ) ; ts.add( 6 ) ; ts.add( 2 ) ; ts.add( 77 ) ; ts.stream().forEach(System. out ::println) ; } } Differences between HashSet, TreeSet, and LinkedHashSet public class J_HashTable { public static void main (String[] args) { Hashtable hashtable= new Hashtable<>() ; hashtable.put( "Alice" , 890 ) ; hashtable.put( "Bob" , 987 - 654 - 3210 ) ; //hashtable.put("C", null); //NullPointerException // Characteristics of Hashtable // Synchronized: Thread-safe. // Legacy: Older class, not recommended for new code. // No Nulls: Does not allow null keys or values.//NullPointerException // Iterate over key-value pairs for (String key : hashtable.keySet()) { System. out .println( "Name: " + key + ", Phone: " + hashtable.get(key)) ; } } "What are the differences between Hashtable and HashMap in Java?" HastTable does not allow null key/value , HashMap does allow null key (once)/value(multiple) public class J_HashTable { public static void main (String[] args) { Hashtable hashtable= new Hashtable<>() ; hashtable.put( "Alice" , 890 ) ; hashtable.put( "Bob" , 987 - 654 - 3210 ) ; //hashtable.put("C", null); //NullPointerException // Characteristics of Hashtable // Synchronized: Thread-safe. // Legacy: Older class, not recommended for new code. // No Nulls: Does not allow null keys or values. // Iterate over key-value pairs for (String key : hashtable.keySet()) { System. out .println( "Name: " + key + ", Phone: " + hashtable.get(key)) ; } Hashtable: Does not allow null keys or values. Thread-safe (synchronised). Slower due to synchronisation. HashMap Allows one null key and multiple null values. Not thread-safe (unsynchronized). Better performance in single-threaded environments. What are the characteristics of a Set in Java?How do HashSet, TreeSet, and LinkedHashSet differ? HashSet Key Difference:-> No guaranteed order of elements. TreeSet- Ordering: Sorted in natural order or by a Comparator LinkedHashSet Ordering: Maintains insertion order What are the advantages and disadvantages of using Hashtable? Does not allow null keys or values. Thread-safe (synchronised). Slower due to synchronisation. Set 3.2- Advance Java Questions ✴️Core Java Concepts: 1. What are the main principles of Object-Oriented Programming (OOP)? 2. Explain the difference between == and equals() method in Java. 3. What is a ClassLoader in Java? 4. What is the difference between an abstract class and an interface? 5. What is a singleton class and how do you implement it? ✴️DataStructures Basic 1. How do you implement a linked list in Java? 2. Describe how a HashMap works in Java. 3. Write a program to reverse a string in Java. 4. How would you find the maximum value in an array? 5. Explain the concept of a binary search tree and write code to perform an in-order traversal. ✴️Multithreading and Concurrency 1. What is the difference between Runnable and Callable in Java? 2. Explain the synchronized keyword and its use cases. 3. What are the different ways to create a thread in Java? 4. What is a deadlock and how can it be prevented? 5. What is the volatile keyword in Java? ✴️Java Collections Framework 1. What is the difference between ArrayList and LinkedList? 2. How does a HashSet store elements (or any collection)? 3. Explain the differences between HashMap and TreeMap. 4. How would you sort a list of objects in Java? 5. What is the purpose of the ConcurrentHashMap class? ✴️Exception Handling 1. What are the different types of exceptions in Java? 2. Explain the use of try-catch-finally blocks. 3. How do you create a custom exception in Java? 4. What is the difference between throw and throws? 5. What is the try-with-resources statement in Java? Alright. This is one of those core Java topics where confusion survives for years because people memorize definitions instead of seeing the logic . I’ll be blunt and precise. 1️⃣ What is an Exception? An Exception is a problem that happens during program execution which can be handled by the programmer. Think of an exception as: “Java shouting: something unexpected happened, but you might be able to recover.” Examples: Dividing by zero Accessing an array out of bounds Reading a file that doesn’t exist Simple definition (exam-ready) An Exception is an event that disrupts the normal flow of a program and can be handled using try–catch. Example public class ExceptionExample { public static void main(String[] args) { int a = 10; int b = 0; try { int c = a / b; // ArithmeticException System.out.println(c); } catch (Exception e) { System.out.println("Cannot divide by zero"); e.printStackTrace(); } System.out.println("Program continues..."); — } } ✅ Output: Cannot divide by zero Program continues... Java didn’t crash. It complained politely and moved on. 2️⃣ What is an Error? An Error is a serious problem that happens outside the control of the programmer and should NOT be handled . Think of an error as: “Java screaming: something is fundamentally broken, abort mission.” Examples: Running out of memory Stack overflow due to infinite recursion JVM failure Simple definition An Error represents a serious problem that a reasonable application should not try to catch. Example public class ErrorExample { public static void main(String[] args) { recursiveCall(); } static void recursiveCall() { recursiveCall(); // StackOverflowError } } ❌ Output: Exception in thread "main" java.lang.StackOverflowError Program dies. No recovery. Curtains close. 3️⃣ Types of Exceptions Java divides exceptions very deliberately . This is not arbitrary. A) Checked Exceptions (Compile-time) Checked at compile time Must be handled using try-catch or throws Usually related to external resources Examples: IOException SQLException FileNotFoundException import java.io.FileReader; public class CheckedExceptionExample { public static void main(String[] args) throws Exception { FileReader fr = new FileReader("data.txt"); // FileNotFoundException } } If you don’t handle it → compiler error . B) Unchecked Exceptions (Runtime) Occur at runtime Not forced by compiler Usually due to programming mistakes Examples: ArithmeticException NullPointerException ArrayIndexOutOfBoundsException public class UncheckedExceptionExample { public static void main(String[] args) { String s = null; System.out.println(s.length()); // NullPointerException } } Compiler stays silent. Runtime explodes. C) Errors (Not Exceptions) Caused by JVM/environment Not meant to be handled Examples: OutOfMemoryError StackOverflowError 4️⃣ Class Hierarchy of Exceptions and Errors This hierarchy is the spine of Java exception handling . Memorize it once, understand it forever. Object └── Throwable ├── Exception │ ├── Checked Exceptions │ │ ├── IOException │ │ ├── SQLException │ │ │ └── RuntimeException │ ├── ArithmeticException │ ├── NullPointerException │ ├── ArrayIndexOutOfBoundsException │ └── Error ├── OutOfMemoryError ├── StackOverflowError Key rules hidden inside this tree Throwable is the root of all exceptions and errors Only subclasses of Throwable can be thrown RuntimeException and its children are unchecked Errors are not recoverable 5️⃣ One Code Example Showing Hierarchy in Action public class HierarchyDemo { public static void main(String[] args) { try { int[] arr = new int[3]; System.out.println(arr[5]); // ArrayIndexOutOfBoundsException } catch (RuntimeException e) { System.out.println("Caught RuntimeException"); } catch (Exception e) { System.out.println("Caught Exception"); } } } ✅ Output: Caught RuntimeException Why? Because ArrayIndexOutOfBoundsException is-a RuntimeException , and Java matches the nearest parent first . 6️⃣ Exception vs Error (One-Line Truth Table) Aspect Exception Error Can be handled Yes No Caused by Program logic / external issues JVM / system Package java.lang.Exception java.lang.Error Recovery possible Often Almost never Strong opinion (worth engraving) If your code is throwing Errors, your design is broken. If your code is throwing Exceptions, your logic needs discipline. This topic becomes deadly easy once you stop memorizing and start reading the hierarchy like a family tree . ✴️Java 8 Features 1. What are lambda expressions in Java? Provide an example. 2. Explain the Stream API in Java 8. 3. What are default methods in interfaces? 4. What is a functional interface? 5. How do you use the Optional class? ✴️Design Patterns - https://www.youtube.com/playlist?list=PLXGQ7XfCauHvtZ75y0nCDtjGEXcaDIPOM 1. What is the Singleton pattern and how do you implement it in Java? 2. Explain the Factory pattern with an example. 3. What is the Observer pattern and where is it used? 4. Describe the Decorator pattern and its use case. 5. What is the difference between the Proxy and Adapter patterns? ✴️Database Connectivity 1. How do you connect to a database using JDBC in Java? 2. What is a JDBC driver and how does it work? 3. Explain the difference between Statement and PreparedStatement in JDBC. 4. How do you handle transactions in JDBC? 5. What is the use of ResultSet in JDBC? ✴️Web Development with Java 1. What is the role of the Spring Framework in Java development? 2. Explain the difference between Spring MVC and Spring Boot. 3. How do you manage dependency injection in Spring? 4. What are RESTful web services and how do you create them in Java? 5. What is the purpose of the @RequestMapping annotation in Spring MVC? Buffer reader import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderDemo { public static void main(String[] args) { /* * BufferedReader belongs to java.io package * It is used to read text efficiently using buffering */ BufferedReader br = null; try { // FileReader reads characters from file // BufferedReader wraps FileReader to improve performance br = new BufferedReader(new FileReader("sample.txt")); System.out.println("Reading file using BufferedReader:\n"); String line; // readLine() reads one complete line at a time while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Error while reading file"); e.printStackTrace(); } finally { try { // Always close the stream if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } } } } Set 4 -Selenium Basics **Selenium Architecture and How ChromeDriver and WebDriver Work** - Core concepts of Selenium and how WebDriver interacts with browsers Think of it as a Chain:** - You (Test Script) -> WebDriver -> JSON Wire Protocol -> Browser Driver -> Browser*. - *Example Story:* - Imagine you're sending a letter (your commands) to a friend (browser). You give the letter to a postman (WebDriver) who puts it in a special envelope (JSON Wire Protocol). Xpath Revision - Mastering XPath for effective web element identification. //tbody/tr[2]/following-sibling::tr Preceding//tbody/tr[2]/preceding::td Identify locators using Siblings with Xpath traverse - example Absolute xpath - starts with ‘/’ slash and should start from the top/root of the DOM or html Relative xpath - starts with ‘//’ slash and should start from the somewhere middle of the DOM or html https://rahulshettyacademy.com/AutomationPractice/ //header/div/button[1] Syntax - Relative-xpath/following-sibling::tag[index-next] //header/div/button[1]/following-sibling::button[1] Relative-xpath/preceding-sibling::tag[index-next] //form/div/input[@name='name']/preceding-sibling::label https://rahulshettyacademy.com/angularpractice/ Dynamic xpath file:///C:/Users/Wasim%20Ansari/OneDrive%20-%20GMO%20GlobalSign/Desktop/dynamic%20table.html non-dynamic-xpath/following-sibling::dynamic-xpath-wihtout-any-slash //*[text()='Ann']/following-sibling::td[@id='jillAge'] How to Traverse from child element to parent element with xpath - Example Relative-xpath/parent::tag[index-next]/parent::............................. //header/div/button[1]/parent::div/parent::header/a[0] **Inspection Disabled XPath** - TBD **Shadow DOM Object XPath**- useful : https://www.youtube.com/watch?v=H_ebGoFWCRs&list=PLXGQ7XfCauHs6vWYbHjyxkO4HXoD1wdB8&index=2 https://books-pwakit.appspot.com/ //input[@id='input'] Step 1 - add dependency io.github.sukgu automation 0.1.5 Step 2 - code public class Z_ShadowDOM_Demo { public static WebDriver driver ; public static void iShadow () { driver = new ChromeDriver() ; driver .manage().timeouts().implicitlyWait( 5 , TimeUnit. SECONDS ) ; driver .get( "https://books-pwakit.appspot.com/" ) ; Shadow shadow = new Shadow( driver ) ; WebElement element = shadow.findElementByXPath( "//input[@id='input']" ) ; element.sendKeys( "do it work" ) ; } public static void main (String[] args) { iShadow () ; } } CSS Tag and ID css=<#> css=input#email Tag and class css=<.> css=input.text Or just .class name for example -> .cart-header-navlink Combining Selectors: Combine multiple selectors to pinpoint specific elements. Example: To find a
with class container containing an with id="username" : css div.container inputusername //div[@class='FPdoLc lJ9FBc']//input[@name='btnI'] → xpath for iam feeling lucky google In the browser console (like Chrome DevTools), you can use the $x function followed by an XPath expression to find elements: XPath Example: $x("your_xpath_expression_here") //a[text()='Courses'] CSS Selector Example: To select all tags with the class link : $(".link") Writing xpath without depending on the attribute and just with the help of parent-child tags: For Xpath - //parent-tagName/Child-TagName[optional-index] Example- //form/input[2] For css - parent tag {space} child tag Example - form h2 https://rahulshettyacademy.com/locatorspractice/ Handle increment counter public static void test_DynamicDropDown () { //driver=new ChromeDriver(); driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/dropdownsPractise/" ) ; driver .findElement(By. id ( "divpaxinfo" )).click() ; for ( int i = 0 ; i <= 4 ; i++) { driver .findElement(By. id ( "hrefIncAdt" )).click() ; } } Handle dropdown dynamic drop down //driver=new ChromeDriver(); driver= new ChromeDriver(); driver.get( "https://rahulshettyacademy.com/dropdownsPractise/" ); driver.findElement(By.id( "ctl00_mainContent_ddl_originStation1_CTXT" )).click(); driver.findElement(By.xpath( "//a[@value='BLR']" )).click(); Thread.sleep( 5000 ); //a[@value='MAA'] --- this will try to select the 'chennai' from the source and will fail driver.findElement(By.xpath( "(//a[@value='MAA'])[2]" )).click(); driver.quit(); Avoid hard coded indexes just combine parent and child xpath //driver=new ChromeDriver(); driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/dropdownsPractise/" ) ; driver .findElement(By. id ( "ctl00_mainContent_ddl_originStation1_CTXT" )).click() ; driver .findElement(By. xpath ( "//a[@value='BLR']" )).click() ; Thread. sleep ( 5000 ) ; //a[@value='MAA'] --- this will try to select the 'chennai' from the source and will fail driver .findElement(By. xpath ( "(//a[@value='MAA'])[2]" )).click() ; //or to avoid indexing driver .findElement(By. xpath ( "//div[@id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[@value='MAA']" )).click() ; driver .quit() ; Handling AutoSuggestive dropdowns using Selenium public class D_AutoSuggestive { public static WebDriver driver ; public static void AutoSuggest () { driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/dropdownsPractise/" ) ; driver .findElement(By. id ( "autosuggest" )).click() ; driver .findElement(By. id ( "autosuggest" )).sendKeys( "IND" ) ; for ( int i = 0 ; i < 3 ; i++) { driver .findElement(By. id ( "autosuggest" )).sendKeys(Keys. DOWN ) ; } driver .findElement(By. id ( "autosuggest" )).sendKeys(Keys. ENTER ) ; } public static void main (String[] args) { AutoSuggest () ; }} Add to cart an specific Product public static void Add_Cucumber_To_Cart () throws InterruptedException { driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/seleniumPractise/" ) ; List allproducts = driver .findElements(By. cssSelector ( "h4.product-name" )) ; for ( int i = 0 ; i < allproducts.size() ; i++) { String myproduct = allproducts.get(i).getText() ; if (myproduct.contains( "Cucumber" )) { driver .findElement(By. xpath ( "//div[3]//div[3]//button[1]" )).click() ; } } } Synchronization usage in Selenium webdriver An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0.Once set, the implicit wait is set for the life of the WebDriver object instance 'driver'. driver .manage().timeouts().implicitlyWait(10, TimeUnit. SECONDS ); An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. u WebDriverWait wait = new WebDriverWait( driver , 10); WebElement element = wait .until(ExpectedConditions. elementToBeClickable(By.linkText( "Conditions of Use" ))); Handling mouse action public class L_MouseAction { public static WebDriver driver ; public static void MouseAmazon () { driver = new ChromeDriver() ; driver .get( "https://www.amazon.in/" ) ; WebElement signinlink=WaitUtils. ElementClickable ( driver , By. id ( "nav-link-accountList" ) , 10 ) ; signinlink.click() ; } public static void main (String[] args) { MouseAmazon () ; } } public class M_SearchWithUpperCase { public static WebDriver driver ; public static void SearchWithUpperCase () { driver = new ChromeDriver() ; driver .get( "https://www.amazon.in/" ) ; WebElement searchBox=WaitUtils. ElementClickable ( driver , By. xpath ( "//input[@id='twotabsearchtextbox']" ) , 10 ) ; Actions act= new Actions( driver ) ; //act.moveToElement(searchBox).build().perform(); act.moveToElement(searchBox).click().keyDown(Keys. SHIFT ).sendKeys( "the wolf" ).build().perform() ; } public static void main (String[] args) { SearchWithUpperCase () ; } } Window handle public static void WindowSwitch () { driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/loginpagePractise/" ) ; driver .manage().window().maximize() ; WebElement blinkinLink_openin_new_windw = driver .findElement(By. xpath ( "//a[@class='blinkingText']" )) ; blinkinLink_openin_new_windw.click() ; Set window_ids = driver .getWindowHandles() ; Iterator itr = window_ids.iterator() ; String Parent_window = itr.next() ; String child_window = itr.next() ; driver .switchTo().window(child_window) ; String myemailid = driver .findElement(By. xpath ( "//a[normalize-space()='mentor@rahulshettyacademy.com']" )).getText() ; driver .switchTo().window(Parent_window) ; WebElement useridBox = driver .findElement(By. xpath ( "//input[@id='username']" )) ; useridBox.click() ; useridBox.sendKeys(myemailid) ; } Frame Calendar package s1_SeleniumBasics ; import Utils.WaitUtils ; import org.openqa.selenium.By ; import org.openqa.selenium.Keys ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.WebElement ; import org.openqa.selenium.chrome.ChromeDriver ; import org.openqa.selenium.support.ui.Select ; public class O_CalenderSpecific { public static WebDriver driver ; public static void CalenderSpecific () throws InterruptedException { driver = new ChromeDriver() ; driver .get( "https://www.tutorialspoint.com/selenium/practice/date-picker.php" ) ; driver .manage().window().maximize() ; WebElement cal_icon = driver .findElement(By. xpath ( "//input[@id='datetimepicker1']" )) ; cal_icon.click() ; WebElement year= WaitUtils. ElementClickable ( driver , By. cssSelector ( ".numInput" ) , 10 ) ; year.clear() ; year.sendKeys( "1989" ) ; Thread. sleep ( 10000 ) ; WebElement monthDropdown = driver .findElement(By. xpath ( "//select[@aria-label='Month']" )) ; monthDropdown.click() ; monthDropdown.sendKeys( "October" ) ; monthDropdown.sendKeys(Keys. ENTER ) ; String date= "20" ; WebElement Date = driver .findElement(By. xpath ( "//span[text( )='" +date+ "']" )) ; Thread. sleep ( 10000 ) ; } public static void main (String[] args) throws InterruptedException { CalenderSpecific () ; Calendar package s1_SeleniumBasics ; import org.openqa.selenium.By ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.chrome.ChromeDriver ; public class E_DefaultCalenderDate { public static WebDriver driver ; public static void Cal_auto_date () throws InterruptedException { driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/dropdownsPractise/" ) ; driver .findElement(By. id ( "ctl00_mainContent_ddl_originStation1_CTXT" )).click() ; driver .findElement(By. xpath ( " //a[@value='BLR'] " )).click() ; Thread. sleep ( 5000 ) ; //a[@value='MAA'] --- this will try to select the 'chennai' from the source and will fail so rather use next line //driver.findElement(By.xpath("(//a[@value='MAA'])[2]")).click(); //or to avoid indexing use parent-xpath//child-xpath ////div[@id='ctl00_mainContent_ddl_destinationStation1_CTNR'] selects the complete destination window driver .findElement(By. xpath ( " //div[@id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[@value='MAA'] " )).click() ; driver .findElement(By. cssSelector ( " .ui-state-default.ui-state-highlight " )).click() ; } public static void main (String[] args) throws InterruptedException { Cal_auto_date () ; } } JavaScript Executor package s1_SeleniumBasics ; import org.openqa.selenium.JavascriptExecutor ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.chrome.ChromeDriver ; import java.util.concurrent.TimeUnit ; public class U_JavaScript_Demo { public static WebDriver driver ; public static void sendKeys_usingJSE () { driver = new ChromeDriver() ; driver .manage().timeouts().implicitlyWait( 5 , TimeUnit. SECONDS ) ; driver .get( "https://rahulshettyacademy.com/seleniumPractise/#/" ) ; //document.getElementsByClassName('search-keyword') JavascriptExecutor jse=(JavascriptExecutor) driver ; /* Type Casting: The (JavascriptExecutor) part is a type cast, which converts the driver object to the JavascriptExecutor type. */ /* Purpose: This allows the use of the executeScript and executeAsyncScript methods provided by the JavascriptExecutor interface. */ jse.executeScript( " document . getElementsByClassName ('search-keyword')[0]. value ='Cucumber';" ) ; } public static void main (String[] args) { sendKeys_usingJSE () ; } } How to Perform Scrolling with in table and Window level using JavaScriptExecutor To click JavascriptExecutor js2 = (JavascriptExecutor) driver ; js2 .executeScript( "arguments[0].click();" , closebtn ); js2 .executeScript( "arguments[0].click();" , closebtn ); To send key jse .executeScript( "document.getElementById('email').value='wasim1065@gmail.com';" ); //the browser window is vertically scrolled down by 1000 pixels Scroll down jse .executeScript( "window.scrollBy(0,1000)" ); u Page load Jse.executeScript( "return document.readyState" ). How to take Screenshots in Selenium package s1_SeleniumBasics ; import org.openqa.selenium. ; import org.openqa.selenium.chrome.ChromeDriver ; import org.openqa.selenium.TakesScreenshot ; import org.apache.commons.io.FileUtils ; import java.io.File ; import java.io.IOException ; import java.util.List ; public class P_ScreenShot { public static WebDriver driver ; public static void myss () throws InterruptedException , IOException { driver = new ChromeDriver() ; driver .get( "https://rahulshettyacademy.com/seleniumPractise/" ) ; List allproducts = driver .findElements(By. cssSelector ( " h4 . product-name " )) ; for ( int i = 0 ; i < allproducts.size() ; i++) { String myproduct = allproducts.get(i).getText() ; if (myproduct.contains( "Cucumber" )) { driver .findElement(By. xpath ( " //div[3]//div[3]//button[1] " )).click() ; break; } } // Capture the screenshot after adding the product to the cart File srcFile = ((TakesScreenshot) driver ).getScreenshotAs(OutputType. FILE ) ; // Specify the destination where the screenshot will be saved File destFile = new File( "src/main/java/Utils/myss.png" ) ; FileUtils. copyFile (srcFile , destFile) ; } public static void main (String[] args) throws InterruptedException , IOException { myss () ; } } List in Automation package s1_SeleniumBasics ; import org.openqa.selenium.By ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.WebElement ; import org.openqa.selenium.chrome.ChromeDriver ; import java.util.List ; import java.util.concurrent.TimeUnit ; public class Q_ListinAutomation { public static void main (String[] args) { WebDriver driver = new ChromeDriver() ; driver.manage().timeouts().implicitlyWait( 10 , TimeUnit. SECONDS ) ; driver.get( "https://rahulshettyacademy.com/seleniumPractise/#/offers" ) ; //List tablerows=driver.findElements(By.xpath("//table/tbody/tr")); List tablerows=driver.findElements(By. cssSelector ( " tr " )) ; for (WebElement iter:tablerows) { List column=iter.findElements(By. xpath ( " td " )) ; String get_value=column.get( 2 ).getText() ; System. out .println(get_value) ; } } } Table Handling public class TableHand { public static WebDriver driver ; public static void Table_me () throws InterruptedException { driver = new ChromeDriver() ; driver .manage().timeouts().implicitlyWait( 5 , TimeUnit. SECONDS ) ; driver .get( "https://rahulshettyacademy.com/seleniumPractise/#/offers" ) ; WebElement FifthRowSecondElement = driver .findElement(By. xpath ( " //table/tbody/tr[5]/td[2] " )) ; String s = FifthRowSecondElement.getText() ; System. out .println(s) ; } public static void main (String[] args) throws InterruptedException { Table_me () ; } } Headless public static void myss1 () throws InterruptedException , IOException { ChromeOptions chrome_options = new ChromeOptions() ; chrome_options.addArguments( "--headless" ) ; // Run Chrome in headless mode driver = new ChromeDriver(chrome_options) ; Shadow DOM Object public class Z_ShadowDOM_Demo { public static WebDriver driver ; public static void iShadow () { driver = new ChromeDriver() ; driver .manage().timeouts().implicitlyWait( 5 , TimeUnit. SECONDS ) ; driver .get( "https://books-pwakit.appspot.com/" ) ; Shadow shadow = new Shadow( driver ) ; WebElement element = shadow.findElementByXPath( "//input[@id='input']" ) ; element.sendKeys( "do it work" ) ; } public static void main (String[] args) { iShadow () ; } } Set 5-Selenium Advanced very good refer - https://drive.google.com/file/d/14bjJxzYNbCDmDR1sASY4w6Lo1xHMn_8g/view?usp=sharing Understanding what to automate and choosing the right framework. Identify What to Automate : Repeating Tasks, Critical Paths, Complex Scenarios Decide What Not to Automate:Rare ly Used Features, Short -Term Projects,Highly Subjective Tests(Things like the visual appearance of a page can be tricky to automate because they often require human judgement). Choose the Right Tools: For example, if you’re testing a web application, you might use Selenium. If it’s an API, you might use Rest Assured. Create a Structure: Organise Your Tests & Reusable Components Update with latest Selenium Version - Selenium Manager From Selenium 4.6.0 : Selenium 4.6.0 includes improved integration with WebDriverManager. WebDriverManager is a library that automates the management of WebDriver binaries (e.g., ChromeDriver, GeckoDriver) required by Selenium. This integration simplifies the setup and maintenance of WebDriver binaries, ensuring that the correct version is automatically downloaded and used according to your Selenium configuration. create a generic method for explicit waits Step 1 - package Utils ; import org.openqa.selenium.By ; import org.openqa.selenium.WebDriver ; import org.openqa.selenium.WebElement ; import org.openqa.selenium.support.ui.ExpectedConditions ; import org.openqa.selenium.support.ui.WebDriverWait ; import java.time.Duration ; public class WaitUtils { public static WebElement mywaitforclickable (WebDriver driver , By locator ,int timeunitinSeconds) { WebDriverWait wait= new WebDriverWait(driver , Duration. ofSeconds (timeunitinSeconds)) ; return wait.until(ExpectedConditions. elementToBeClickable (locator)) ; }} Step 2 - public class K_ExplicitWait_with_custom_explicit { public static WebDriver driver ; public static void SearchGoogleAutoSuggest () { driver = new ChromeDriver() ; driver .get( "https://www.google.com/" ) ; WebElement search_box= WaitUtils. mywaitforclickable ( driver , By. name ( "q" ) , 5 ) ; search_box.sendKeys( "IPL" ) ; WaitUtils. visibilityOfElementLocated_Self ( driver , By. xpath ( "//ul[@role='listbox']" ) , 10 ) ; for ( int i = 0 ; i < 4 ; i++) { search_box.sendKeys(Keys. DOWN ) ; } search_box.sendKeys(Keys. ENTER ) ; } public static void main (String[] args) { SearchGoogleAutoSuggest () ; } } Design Pattern , Singleton Class What is singleton class package com.testcompany.webdriver ; public class SingleTonDemo { private static SingleTonDemo INSTANCE ; private SingleTonDemo () { // Private constructor to prevent instantiation } public static SingleTonDemo getInstance () { if ( INSTANCE == null ) { INSTANCE = new SingleTonDemo() ; } return INSTANCE ; } public static void TestSingleTonMethod () { System. out .println( "test a single method" ) ; } } How to call a singleton class package com.testcompany.webdriver ; public class CallSignletonDemo { public static void main (String[] args) { //SingleTonDemo obj=new SingleTonDemo(); //'SingleTonDemo()' has private access in 'com.testcompany.webdriver.SingleTonDemo' --> error SingleTonDemo. getInstance (). TestSingleTonMethod () ; } } How to do we implement Singleton class in driver initialization Certainly! Here's a step-by-step explanation of your `CreateDriver` class: 1. Singleton Instance private static CreateDriver INSTANCE; ``` - Explanation: This line declares a static variable `INSTANCE` of type `CreateDriver`. This will hold the single instance of the `CreateDriver` class to ensure that only one instance is created and used throughout the application. 2. Private Constructor private CreateDriver () { } ``` - Explanation: The constructor is marked as private to prevent instantiation from outside the class. This is a crucial step in implementing the Singleton pattern, which ensures that the class can only be instantiated internally. 3. Static Method to Get the Instance public static CreateDriver getINSTANCE () { if (INSTANCE == null ) { INSTANCE = new CreateDriver(); } return INSTANCE; } ``` - Explanation: The `getINSTANCE` method provides a global point of access to the `CreateDriver` instance. It checks if the `INSTANCE` is `null` (i.e., the class has not been instantiated yet). If so, it creates a new instance of `CreateDriver`. This ensures that only one instance of the class is ever created. Explain framework https://drive.google.com/file/d/1-ZgOnXbo9BuUBnqcFg4I97Fiz0ZH7zRi/view?usp=drivesdk Hybrid - Framework (Page Object Model) https://github.com/wazans/MyHybridFramework_20july2024 Rest Assured Framework (Cucumber) https://github.com/wazans/RESTAssured_Cucumber Extent Report - OneDrive - GMO GlobalSign\extent report.docx https://www.linkedin.com/posts/prince-kumar-7b389a68_%F0%9D%97%98%F0%9D%98%85%F0%9D%98%81%F0%9D%97%B2%F0%9D%97%BB%F0%9D%98%81-%F0%9D%97%A5%F0%9D%97%B2%F0%9D%97%BD%F0%9D%97%BC%F0%9D%97%BF%F0%9D%98%81-%F0%9D%97%B6%F0%9D%97%BB-%F0%9D%97%95%F0%9D%97%97%F0%9D%97%97-%F0%9D%97%96%F0%9D%98%82%F0%9D%97%B0%F0%9D%98%82%F0%9D%97%BA%F0%9D%97%AF%F0%9D%97%B2%F0%9D%97%BF-activity-7237159754144358400-ab-J?utm_source=share&utm_medium=member_android POI API - OneDrive - GMO GlobalSign\POI API.docx DataProvider+Excel Sure, let's simplify the process by creating a DataProvider that reads from an Excel file and integrates it into your test class. We'll add the necessary logic to read a single username and password from the Excel file and use it in your tests. Step 1: Add Dependencies for Apache POI Ensure your `pom.xml` includes dependencies for Apache POI: ```xml org.apache.poi poi 5.2 .3 org.apache.poi poi-ooxml 5.2 .3 ``` ### Step 2: Create a Utility Class to Read Excel Create a utility class `ExcelUtil.java` to read data from an Excel file: package com.testcompany.utils; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; public class ExcelUtil { private Workbook workbook; private Sheet sheet; public ExcelUtil (String excelFilePath, String sheetName) throws IOException { FileInputStream fis = new FileInputStream(excelFilePath); workbook = new XSSFWorkbook(fis); sheet = workbook.getSheet(sheetName); } public String getCellData ( int rowNum, int colNum) { Row row = sheet.getRow(rowNum); Cell cell = row.getCell(colNum); return cell.getStringCellValue(); } public Object[][] getExcelData() { int rowCount = sheet.getLastRowNum() + 1 ; int colCount = sheet.getRow( 0 ).getLastCellNum(); Object[][] data = new Object[rowCount - 1 ][colCount]; for ( int i = 1 ; i < rowCount; i++) { for ( int j = 0 ; j < colCount; j++) { data[i - 1 ][j] = getCellData(i, j); } } return data; } } ``` ### Step 3: Create a DataProvider Method Add a DataProvider method in your test class `LoginTest_DataProvider_Excel.java`: package com.testcompany.tests; import com.testcompany.base.BaseTest; import com.testcompany.pages.LoginPage_PageFactory; import com.testcompany.utils.ExcelUtil; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; public class LoginTest_DataProvider_Excel extends BaseTest { /* Instance of LoginPage. */ public LoginPage_PageFactory lp; public LoginTest_DataProvider_Excel () throws IOException { super (); } @DataProvider (name = "loginData" ) public Object[][] loginDataProvider() throws IOException { ExcelUtil excelUtil = new ExcelUtil( "src/test/resources/loginData.xlsx" , "Sheet1" ); return excelUtil.getExcelData(); } @BeforeMethod public void BeforeTest_intiliasie (String username, String password) { /* Calls the initialization() method from BaseTest to set up the WebDriver. */ initialization(); /* Initializes the LoginPage instance (lp). */ lp = new LoginPage_PageFactory(driver); lp.enterUsername(username); lp.enterPassword(password); } @Test (dataProvider = "loginData" ) public void LoginTestSequence (String username, String password) { /* BeforeTest_intiliasie is called with data from DataProvider. */ lp.selectLocation(); lp.clickLoginButton(); } /* Flow Overview: - LoginTest Constructor: Calls BaseTest constructor to load properties. - BeforeTest_intiliasie Method: Calls initialization method to set up WebDriver. Initializes LoginPage and enters username and password. - LoginTestSequence Method: Selects location and clicks login button using LoginPage methods. */ } ``` ### Step 4: Prepare the Excel File Create an Excel file `loginData.xlsx` in `src/test/resources` with the following structure: | Username | Password | |----------|----------| | Admin | Admin123 | ### Explanation 1. **ExcelUtil Class**: This class reads data from the Excel file. 2. **DataProvider Method**: This method uses the `ExcelUtil` class to fetch data from the Excel file and provide it to the test methods. 3. **Test Methods**: The test methods are annotated with `@Test(dataProvider = "loginData")`, which allows them to use the data provided by the DataProvider. ### Running the Tests You can run the tests using your `pom.xml` or directly from your IDE. Log4j - OneDrive - GMO GlobalSign\Log 4j.docx Set 6-TestNG OneDrive - GMO GlobalSign\TestNG.docx Also, testng.pdf https://github.com/wazans/TestNgAndSomeOtherCodes/blob/master/Day5_TestNG_part2/src/test/java/ExcelDemo/ExcelDemo.java Failed Test Cases- Handling and managing failed test cases effectively. Step 1 - Create a class that implements ITestListener Step 2 @the class level ->> @Listeners(Utils.ListenerTest.class) Or @the testng.xml suite level ->> Grouping Test Cases @Test(groups = {"sanity", "regression"}) public void testLogin() Importance of Assertions in Automation testing and how to use them Assert.assertEquals(actualTitle, expectedTitle, "Page title doesn't match expected title"); Here are some additional examples of TestNG assertions you can use in your tests: 1 . **Assert Equals**: Assert.assertEquals(actualValue, expectedValue, "Values do not match!" ); ``` 2 . **Assert Not Equals**: Assert.assertNotEquals(actualValue, expectedValue, "Values should not match!" ); ``` 3 . **Assert True**: Assert.assertTrue(condition, "Condition is not true!" ); ``` 4 . **Assert False**: Assert.assertFalse(condition, "Condition is not false!" ); ``` 5 . **Assert Null**: Assert.assertNull(object, "Object is not null!" ); ``` 6 . **Assert Not Null**: Assert.assertNotNull(object, "Object is null!" ); ``` 7 . **Assert Array Equals**: Assert.assertEquals(actualArray, expectedArray, "Arrays do not match!" ); ``` 8 . **Assert Contains**: Assert.assertTrue(driver.getPageSource().contains( "Expected Text" ), "Page source does not contain expected text!" ); ``` 9 . **Assert Not Contains**: Assert.assertFalse(driver.getPageSource().contains( "Unexpected Text" ), "Page source contains unexpected text!" ); ``` 10 . **Assert Fail**: Assert.fail( "Test failed due to specific reason!" ); ``` These assertions can be used to validate various aspects of your application and ensure that your tests cover the expected behaviour. Trigger testng.xml from pom.xml After org.apache.maven.plugins maven-surefire-plugin 3.0.0-M5 src/testng.xml Maven Life cycle Open the Maven Tool Window: Navigate to View > Tool Windows > Maven to open the Maven tool window. Alternatively, you can click on the Maven icon on the right sidebar. To run the complete Maven lifecycle, you typically need to execute the install phase, as it includes all previous phases up to install . Right-click on install and select Run 'install' . Set 7-Rest Assured and API API Testing API is the middle layer between presentation layer i.e. UI and the database layer. — Types of HTTP requests POST - creating a resources, non-idempotent (can create duplicate resources) PUT - creating or update a resource, idempotent (can not create duplicate resources) "Idempotent" generally refers to a property of an operation where applying it multiple times has the same effect as applying it once. PATCH - partial modification to the resource , like post it is non-idempotent. DELETE - Delete the resources API Headers Authorization Content Type text/json, text/html Date Accept HTTP Status Codes 405 - method not allowed Authorization vs authentication Needs to verify WebService Web service is a Managed code Invoked with the help of http requests All Web Services are apis…. Needs a network All apis are not webservices – does not need network/internet. can run locally where two applications communicates and apis are exposed with the help of local files Rest Assured Assertions Techniques for making assertions in API testing with Rest Assured. String actualAverage = response .jsonPath().getString( "find { it.player == '" + player + "' }.average" ) ; Assert. assertEquals ( "Average for player " + player + " did not match" , expectedAverage , actualAverage) ; REST vs SOAP **REST**: Uses HTTP, supports multiple formats (JSON, XML), stateless , simpler, faster, ideal for web APIs. **SOAP**: Protocol-based, uses XML, supports stateful operations, more secure, ideal for enterprise services. Stateless vs stateful Sure! Here's a simple explanation of stateless and stateful concepts in REST: - ** Stateless **: In a stateless REST architecture, each request from the client to the server must contain all the information the server needs to fulfill that request. The server does not store any information about the client between requests. Every request is independent and self-contained. This makes the system more scalable and reliable because each request is treated as a new interaction. - ** Stateful **: In a stateful architecture, the server keeps track of the client’s state between requests. This means that the server remembers previous interactions and may use that information for subsequent requests . While this can simplify client interactions with the server (since the server remembers the client’s context), it can also make the system more complex and less scalable because of the need to manage and store client states. In RESTful services, statelessness is preferred because it leads to simpler, more scalable, and more reliable systems. Simple JsonPath and extract import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class ExtractJsonExample { public static void main (String[] args) { // Base URI of the REST API RestAssured.baseURI = "http://localhost:3000" ; // Perform a GET request and extract response Response response = given() .header( "Content-Type" , "application/json" ) .when() .get( "/profile" ) .then() .statusCode( 200 ) .extract().response(); // Extract JSONPath object from the response JsonPath jsonPath = response.jsonPath(); // Extract specific data using JSONPath String name = jsonPath.getString( "name" ); String role = jsonPath.getString( "role" ); String email = jsonPath.getString( "email" ); // Print extracted values System.out.println( "Name: " + name); System.out.println( "Role: " + role); System.out.println( "Email: " + email); } } To use POJO and serialization/deserialization for the endpoint `http://localhost:3000/profile` with the default response, follow these steps: Create the POJO Class: Step 1 -Define the POJO class with necessary fields, constructors, getters, and setters. Step 2 - Create a Utility Class: Create a utility class to construct the request body using the POJO and serialise it into a JSON string. Step 3 - Use the Utility Class in Step Definitions: In the step definitions, use the utility class to get the request body and send it in the API request. Step 1 - package com.example.POJO ; public class Friends_CallmePOJO { private int id ; private String firstname ; private String lastname ; private int age ; private String email ; Friends_CallmePOJO () { //Default constructor } /* The parameterized constructor Friends(String id, String firstname, String lastname, int age, String email) allows the creation of an object with initial values for all fields. */ public Friends_CallmePOJO ( int id , String firstname , String lastname , int age , String email) { this . id = id ; this . firstname = firstname ; this . lastname = lastname ; this . age = age ; this . email = email ; } public int getId () { return id ; } public void settId ( int id) { this . id = id ; } public String getFirstname () { return firstname ; } public void setFirstname (String firstname) { this . firstname =firstname ; } public String getLastname () { return lastname ; } public void setLastname (String lastname) { this . lastname = lastname ; } public int getAge () { return age ; } public void setAge ( int age) { this . age = age ; } public String getEmail () { return email ; } public void setEmail (String email) { this . email = email ; } } Step 2- public class RequestBodyUtils_CallingPOJO { static ObjectMapper objectMapper = new ObjectMapper() ; //ObjectMapper is a class of Jakson library // writeValueAsString method // objectMapper object public static String CreateBodyForFriend_withPojo () throws JsonProcessingException { Friends_CallmePOJO friend= new Friends_CallmePOJO( 1 , "pojo_firstname" , "pojo_lastname" , 65 , "pojo@pojo.com" ) ; //(serialising) friend object is a java object -> with the help of objectMapper object -> get it converted to JSON string return objectMapper .writeValueAsString(friend) ; } } Step 3 - call the pojo class request body @When ( "I send a POST request with the help of JSON to {string}" ) public void iSendAPOSTRequestWithTheHelpOfJSONTo (String endpoint) throws JsonProcessingException { String requestbody_with_pojo= RequestBodyUtils_CallingPOJO. CreateBodyForFriend_withPojo () ; response = given ().contentType( "application/json" ).body(requestbody_with_pojo).post(endpoint) ; } Json schema validator Add Dependencies: Include Rest Assured and JSON Schema Validator in your pom.xml . Create JSON Schema: Create friends_schema.json in src/test/resources . Write Step Definition: Update your step definition to include schema validation. Example - response.body(JsonSchemaValidator.matchesJsonSchemaInClasspath("friends_schema.json")) Create a json schema with the help of response body -> under classpath keep it as .json -> use JsonSchemaValidator class -> matchesJsonSchemaInClasspath Method response .then() .assertThat() .statusCode( 201 ) .body(JsonSchemaValidator. matchesJsonSchemaInClasspath ( "friends_schema.json" )) .body( "firstname" , equalTo ( "post_with_json_shcema" )) ; Assertion in Rest Assured public class RestAssuredAssertionsExample { public static void main (String[] args) { // Base URI of the REST API RestAssured.baseURI = "http://localhost:3000" ; // Perform a GET request and extract response Response response = given() .header( "Content-Type" , "application/json" ) .when() .get( "/profile" ) .then() .assertThat() .statusCode( 200 ) // Asserting the status code .body( "name" , notNullValue()) // Asserting 'name' field is not null .body( "role" , equalTo( "Developer" )) // Asserting 'role' field value .body( "email" , containsString( "@example.com" )) // Asserting 'email' contains '@example.com' .extract().response(); // Extract JSONPath object from the response JsonPath jsonPath = response.jsonPath(); // Extract specific data using JSONPath String name = jsonPath.getString( "name" ); String role = jsonPath.getString( "role" ); String email = jsonPath.getString( "email" ); // Print extracted values System.out.println( "Name: " + name); System.out.println( "Role: " + role); System.out.println( "Email: " + email); // Additional assertions in Java assertNotNull(name, "Name should not be null" ); assertEquals(role, "Developer" , "Role should be 'Developer'" ); assertTrue(email.contains( "@example.com" ), "Email should contain '@example.com'" ); } // Helper methods for additional assertions private static void assertNotNull (String value, String message) { if (value == null ) { throw new AssertionError(message); } } private static void assertEquals (String actual, String expected, String message) { if (!actual.equals(expected)) { throw new AssertionError(message); } } private static void assertTrue ( boolean condition, String message) { if (!condition) { throw new AssertionError(message); } } } To perform an assertion that verifies the JSON response where the id is "1" and the firstname is "John" Response response = (Response) RestAssured. given () .contentType( "application/json" ) .body(requestbody_with_pojo) .post(endpoint) .then() .assertThat() .statusCode( 201 ) .body( "find { it.id == '1' }.firstname" , equalTo ( "John" )) ; POSTMAN - C:\Users\Wasim Ansari\OneDrive - GMO GlobalSign\Documents\old back up\POSTMAN or C:\Users\Wasim Ansari\OneDrive - GMO GlobalSign\Documents\TunesKit Screen Recorder\Converted\API Testing (SOAPPostman) Set 8-Cucumber Cucumber Cucumber allows developers,QAs and non-technical or business participant to write features and scenarios in a plain text file using Gherkin lang. package com.example.runners ; import org.junit.runner. RunWith ; import io.cucumber.junit.Cucumber ; import io.cucumber.junit. CucumberOptions ; //Focus //Grow //Thrive @RunWith (Cucumber. class ) @CucumberOptions ( features = "src/test/resources/features" , // Path to your feature files //glue = {"com.example.stepdefinitions","com.example.hooks"}, // Package containing your step definitions and hook glue = { "com.example.stepdefinitions" } , tags = "@post_with_json_shcema" // Tags to filter scenarios // dryRun = true, // // Enable dryRun , When set to true, // // Cucumber will check for missing step definitions but won’t execute the scenarios. // strict = true // Fail the test suite if there are undefined or pending steps ) public class TestRunner { } We can achieve a data driven approach in cucumber with the help of Examples keyword. The scenario outline in feature file should be accompanied by the “Example” keyword to pass multiple data at run time Tags tags = "@post_with_json_shcema" // Tags to filter scenarios Dry run The @CucumberOptions ahas a dry run parameter which will throw error if set to true for an step without step definition Run cucumber tests parallely JVM parallel plugin Reports plugin = { "pretty" , "json:target/cucumber-report.json" , "html:target/cucumber-report_wasim99.html" } // Report plugins Profile Create the cucumber.yml File In the root directory of your project, create the cucumber.yml file with the following content: default: --glue step_definitions --plugin pretty --plugin json:target/cucumber-report.json --plugin html:target/cucumber-report.html profile1: --tags @profile1 profile2: --tags @profile2 Run it -> mvn test -Dcucumber.options="--profile profile1" Set 9-Jenkins http://localhost:8080/login?from=%2Fmanage%2F C:\Users\Wasim Ansari\OneDrive - GMO GlobalSign\Documents\old back up\Jenkins scheduling builds Jenkins uses a cron-like syntax for scheduling builds. Here’s a detailed explanation of the fields used in the cron syntax: Syntax Format: MINUTE HOUR DAY_OF_MONTH MONTH DAY_OF_WEEK Fields Explained: MINUTE: The minute within the hour when the job should run (0-59). HOUR: The hour of the day when the job should run (0-23, where 0 is midnight). DAY_OF_MONTH: The day of the month when the job should run (1-31). MONTH: The month when the job should run (1-12). DAY_OF_WEEK: The day of the week when the job should run (0-7, where both 0 and 7 represent Sunday). Set 10- JIRA & Agile Agile - means adaptive and response to change Discovery > Design > Coding > Testing > Deployment > Maintenance Agile’s innovative approach deliver “value” i.e. the logical pieces of working software Plan > Design > Develop > Test > Release > Feedback —Agile Scrum - is an agile methodologies (Lean, Kanban , Crystals etc) are other In scrum Product Owner create the backlog the final product needs Scrum team gets together to plan which work on first from the backlog - Sprint Planning During the Sprint The team meets to communicate the issue and progress - Scrum meeting or Daily Scrum At the end of the Sprint the PO organises a Sprint review meeting where the team demo what they completed since the last sprint Sprint retrospective - What went well,what could be better , what did not went well Product Owner creates backlog -> Sprint Planning -> Daily Scrum -> Sprint Review -> Sprint Retrospective In Agile, velocity is a metric that measures the amount of work a team completes during a sprint. Numeric Example Let's say a team uses story points to estimate the work: Sprint 1: User Story A: 5 points User Story B: 8 points User Story C: 3 points Total completed: 5 + 8 + 3 = 16 points Sprint 2: User Story D: 5 points User Story E: 8 points User Story F: 5 points Total completed: 5 + 8 + 5 = 18 points Sprint 3: User Story G: 8 points User Story H: 8 points User Story I: 3 points Total completed: 8 + 8 + 3 = 19 points Calculating Average Velocity Average Velocity=16+18+19/3=53/3=17.67 points per sprint Iteration and Incremental are two different things Scrum vs Kanban vs LEAN Scrum is structured and time-boxed with defined roles and ceremonies, suitable for projects requiring regular assessment and adaptation. Imagine a team building a new feature for a mobile app. They break down the work into smaller tasks (user stories) and plan to complete a set amount of tasks in a 2-week sprint. Every day, they hold a short stand-up meeting to discuss progress and obstacles. At the end of the sprint, they review the work done and discuss improvements for the next sprint. Kanban is flexible and visual, focusing on continuous delivery and managing flow, suitable for ongoing work with less rigid structure. Visualises work items. A team maintaining a website uses a Kanban board with columns for "Backlog," "In Progress," "Code Review," and "Done." They pull tasks from the backlog into "In Progress" based on capacity and move them across the board as work progresses. There are limits to how many tasks can be in each column to ensure focus and prevent bottlenecks. Lean emphasises eliminating waste and optimising the whole process, suitable for improving efficiency and delivering maximum value. A team developing a new product follows Lean principles by frequently releasing small increments to get feedback from customers early and often. They continuously analyze their workflow to remove unnecessary steps, streamline processes, and improve efficiency, ensuring they deliver high-quality products quickly. Burndown Chart ( amount of work vs time) Definition: A burndown chart is a graphical representation that shows the amount of work remaining versus time. Example: Imagine a team has 100 story points to complete in a 10-day sprint. Each day, they update the chart with the remaining points. If they complete 10 points a day, the actual work line will follow the ideal line. If they fall behind, the actual line will be above the ideal line. 100= to complete 10= day sprint 10=sprint points per day is ideal Burnup Chart( Total work vs Completed work) Definition: A burnup chart is a graphical representation that shows both the work completed and the total work over time. Example: Imagine a team has 100 story points to complete in a project. Each day, they update the chart with the amount of work completed. If they complete 10 points a day, the completed work line will rise steadily until it meets the total work line. Total work (the overall goal or amount of work to be done). Completed work (the amount of work that has been finished). _________________________________________________________________________ Set 11- Manual Testing Set 12 -SQL C:\Users\Wasim Ansari\Downloads\all new\SQL https://docs.google.com/document/d/1orykaLGQBx5iWDVV0RHmHBmb9zCoFD5K/edit Set 13- GIT,GITBucket,GITLab GIT - C:\Users\Wasim Ansari\OneDrive - GMO GlobalSign\Documents\old back up\4 Sharing Changes Back to the Server or C:\Users\Wasim Ansari\Downloads\all new\GIT adv Create git account Create git repo git init git add . git remote add origin https://github.com/wazans/MyHybridFramework_20july2024.git git checkout -b main git commit -m "first commit" git push -u origin main Git remote add origin https://github.com/wazans/RESTAssured_Cucumber.git GIT SIKHO GITLab - C:\Users\Wasim Ansari\OneDrive - GMO GlobalSign\Documents\old back up\GITLAB